<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/10/24
 * Time: 10:49
 */

namespace app\api\model;


use constant\config;
use foxyZeng\huyi\HuYiSMS;
use redis\RedisPackage;
use think\Db;
use think\Model;
use think\Cache;
use think\Exception;
use function GuzzleHttp\Psr7\str;

class Common extends Model {
    /*
     *
     * 合并图片二维码
     */
    public static function getbgqrcode($imageDefault, $textDefault, $background, $filename = "", $config = []) {
        //如果要看报什么错，可以先注释调这个header
        if (empty($filename)) header("content-type: image/png");
        //背景方法
        $backgroundInfo   = getimagesize($background);
        $ext              = image_type_to_extension($backgroundInfo[2], false);
        $backgroundFun    = 'imagecreatefrom' . $ext;
        $background       = $backgroundFun($background);
        $backgroundWidth  = imagesx($background);  //背景宽度
        $backgroundHeight = imagesy($background);  //背景高度
        $imageRes         = imageCreatetruecolor($backgroundWidth, $backgroundHeight);
        $color            = imagecolorallocate($imageRes, 0, 0, 0);
        imagefill($imageRes, 0, 0, $color);
        imagecopyresampled($imageRes, $background, 0, 0, 0, 0, imagesx($background), imagesy($background), imagesx($background), imagesy($background));
        //处理了图片
        if (!empty($config['image'])) {
            foreach ($config['image'] as $key => $val) {
                $val       = array_merge($imageDefault, $val);
                $info      = getimagesize($val['url']);
                $function  = 'imagecreatefrom' . image_type_to_extension($info[2], false);
                $res       = $function($val['url']);
                $resWidth  = $info[0];
                $resHeight = $info[1];
                //建立画板 ，缩放图片至指定尺寸
                $canvas = imagecreatetruecolor($val['width'], $val['height']);
                imagefill($canvas, 0, 0, $color);
                //关键函数，参数（目标资源，源，目标资源的开始坐标x,y, 源资源的开始坐标x,y,目标资源的宽高w,h,源资源的宽高w,h）
                imagecopyresampled($canvas, $res, 0, 0, 0, 0, $val['width'], $val['height'], $resWidth, $resHeight);
                $val['left'] = $val['left'] < 0 ? $backgroundWidth - abs($val['left']) - $val['width'] : $val['left'];
                $val['top']  = $val['top'] < 0 ? $backgroundHeight - abs($val['top']) - $val['height'] : $val['top'];
                //放置图像
                imagecopymerge($imageRes, $canvas, $val['left'], $val['top'], $val['right'], $val['bottom'], $val['width'], $val['height'], $val['opacity']);//左，上，右，下，宽度，高度，透明度
            }
        }
        //处理文字
        
        foreach ($textDefault as $value) {
            foreach ($config as $key => $val) {
                $val = array_merge($value, $val);
                
                list($R, $G, $B) = explode(',', $val['fontColor']);
                $fontColor   = imagecolorallocate($imageRes, $R, $G, $B);
                $val['left'] = $val['left'] < 0 ? $backgroundWidth - abs($val['left']) : $val['left'];
                $val['top']  = $val['top'] < 0 ? $backgroundHeight - abs($val['top']) : $val['top'];
                imagettftext($imageRes, $val['fontSize'], $val['angle'], $val['left'], $val['top'], $fontColor, $val['fontPath'], $val['text']);
            }
        }
        
        
        //生成图片
        if (!empty($filename)) {
            $res = imagejpeg($imageRes, $filename, 90);
            //保存到本地
            imagedestroy($imageRes);
        } else {
            imagejpeg($imageRes);
            //在浏览器上显示
            imagedestroy($imageRes);
        }
    }
    
    /**
     * 添加资源返回ID
     * @param $resources
     * @return array
     */
    public function addResourceIds($resources) {
        
        $resource_ids = [];
        foreach ($resources as $item) {
            if (!isset($item['mime_type']) || !isset($item['file_path'])) {
                r_date(null, 300, '资源格式错误');
            }
            $info = Db::connect(config('database.db2'))->table('common_resource')->where('path', $item['file_path'])->find();
            
            if ($info !== null) {
                $resource_ids[] = $info['id'];
            } else {
                $resource_ids[] = Db::connect(config('database.db2'))->table('common_resource')->insertGetId(['mime_type' =>empty($item['mime_type'])?'image/jpeg': $item['mime_type'], 'path' => $item['file_path'], 'size' => $item['size'] ?? 0, 'created_at' => time()]);
            }
        }
        return $resource_ids;
    }
       /**
     * 生成资源数据
     * @param $resources
     * @return array
     */
    public function addResourceListImg($resourcesImg) {
        
        $resource_ids = [];
        foreach($resourcesImg as $value){
            // $headers =  get_headers($value, 1);
            // $mime_type =  getimagesize($value)['mime'];
            $path      = parse_url($value)['path'];
            // if (isset($headers['Content-Length'])) {
            //     $fileSize = $headers['Content-Length'];
            //     $size     = $fileSize;
            // } else {
            //     $size = 0;
            // }
            $info = Db::connect(config('database.db2'))->table('common_resource')->where('path', $path)->find();
            
            if ($info !== null) {
                $resource_ids[] = $info['id'];
            } else {
                $resource_ids[] = Db::connect(config('database.db2'))->table('common_resource')->insertGetId(['mime_type' => 1, 'path' => $path, 'size' => $size ?? 0, 'created_at' => time()]);
            }
            
        }
        return $resource_ids;
    }
    
    public function Calculation($datum, $order_id, $user_id, $state, $secondment = 0) {
        $m = db('order')->field('order.order_id,us.store_id,concat(p.province,c.city,y.county,order.addres) as addres')->join('province p', 'order.province_id=p.province_id', 'left')->join('city c', 'order.city_id=c.city_id', 'left')->join('county y', 'order.county_id=y.county_id', 'left')->join('user us', 'order.assignor=us.user_id', 'left')->where(['order.order_id' => $order_id])->find();
        if ($datum['type'] == 0) {
            $custom_number   = db('custom_material')->where(['id' => $datum['Material_id'], 'store_id' => $m['store_id'], 'status' => 0])->field('number,stock_name')->find();
            $square_quantity = $custom_number['number'];
            $number          = $custom_number['number'] - $datum['square_quantity'];;
            if ($number < 0) {
                return ['code' => 'no', 'msg' => $custom_number['stock_name'] . '库存不足'];
            }
            db('custom_material')->where(['id' => $datum['Material_id'], 'store_id' => $m['store_id']])->update(['number' => round($number, 2)]);
            $Unified        = $datum['Material_id'];
            $reference_cost = 0;
        } elseif ($datum['type'] == 99) {
            $purchase_number = db('purchase_usage')->where(['id' => $datum['Material_id'], 'store_id' => $m['store_id'], 'status' => 3])->field('number,stock_name')->find();
            $square_quantity = $purchase_number['number'];
            $number          = $purchase_number['number'] - $datum['square_quantity'];
            if ($number < 0) {
                
                return ['code' => 'no', 'msg' => $purchase_number['stock_name'] . '库存不足'];
            }
            db('purchase_usage')->where(['id' => $datum['Material_id'], 'store_id' => $m['store_id']])->update(['number' => round($number, 2)]);
            $Unified        = $datum['Material_id'];
            $reference_cost = 0;
        } elseif ($datum['type'] == 98) {
            $cooperation_usage = db('cooperation_usage')->where(['id' => $datum['Material_id'], 'status' => 3])->find();
            $stock             = db('stock')->where(['id' => $cooperation_usage['stock_id']])->find();
            $square_quantity   = db('cooperation_usage')->where(['stock_id' => $cooperation_usage['stock_id'], 'status' => 3, 'latest_cost' => $cooperation_usage['latest_cost']])->sum('number');
            $number            = $square_quantity - $datum['square_quantity'];
            if ((int)$number < 0) {
                return ['code' => 'no', 'msg' => $cooperation_usage['stock_name'] . '库存不足'];
            }
            sendMsg(config('user'), 237619, [0 => $cooperation_usage['stock_name'], 1 => $datum['square_quantity'] . $cooperation_usage['company'], 2 => $m['addres']]);
            $Unified        = db('cooperation_usage')->insertGetId(['stock_name' => $cooperation_usage['stock_name'], 'latest_cost' => $cooperation_usage['latest_cost'], 'number' => '-' . $datum['square_quantity'], 'stock_id' => $cooperation_usage['stock_id'], 'notes' => '时间：' . date('Y-m-d', time()), 'created_time' => time(), 'company' => $cooperation_usage['company']]);
            $reference_cost = $stock['reference_cost'];
        } else {
            $cooperation_usage = db('routine_usage')->where(['id' => $datum['Material_id']])->find();
            
            $stock           = db('stock')->where(['id' => $cooperation_usage['stock_id']])->find();
            $routine_number  = db('routine_usage')->where(['stock_id' => $cooperation_usage['stock_id'], 'latest_cost' => $cooperation_usage['latest_cost'], 'store_id' => $m['store_id'], 'status' => 3])->select();
            $square_quantity = array_sum(array_column($routine_number, 'number'));
            $number          = array_sum(array_column($routine_number, 'number')) - $datum['square_quantity'];
            if ($number < 0) {
                return ['code' => 'no', 'msg' => $routine_number[0]['stock_name'] . '库存不足'];
            }
            
            if ((float)$datum['square_quantity'] < 0) {
                $square = abs($datum['square_quantity']);
            } else {
                $square = '-' . $datum['square_quantity'];
            }
            $Unified = db('routine_usage')->insertGetId(['store_id' => $m['store_id'], 'stock_name' => $cooperation_usage['stock_name'], 'latest_cost' => $cooperation_usage['latest_cost'], 'user_id' => $user_id, 'number' => $square, 'stock_id' => $cooperation_usage['stock_id'], 'status' => $state, 'notes' => $cooperation_usage['notes'], 'adopt' => $cooperation_usage['adopt'], 'voucher' => $cooperation_usage['voucher'], 'created_time' => time(), 'company' => $cooperation_usage['company'], 'secondment' => $secondment]);
            
            $reference_cost = $stock['reference_cost'];
            
        }
        
        return ['code' => 'ok', 'number' => $square_quantity, 'unified' => $Unified, 'reference_cost' => $reference_cost];
    }
    
    // 阿拉伯数字转中文大写金额
    
    public static function NumToCNMoney($amount, $type = 0) {
        if (!is_numeric($amount)) {
            return "要转换的金额只能为数字!";
        }
        
        // 金额为0,则直接输出"零元整"
        if ($amount == 0) {
            return "人民币零元整";
        }
        
        // 金额不能为负数
        if ($amount < 0) {
            return "要转换的金额不能为负数!";
        }
        
        // 金额不能超过万亿,即12位
        if (strlen($amount) > 12) {
            return "要转换的金额不能为万亿及更高金额!";
        }
        
        // 预定义中文转换的数组
        $digital = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
        // 预定义单位转换的数组
        $position = ['仟', '佰', '拾', '亿', '仟', '佰', '拾', '万', '仟', '佰', '拾', '元'];
        
        // 将金额的数值字符串拆分成数组
        
        $amountArr = explode('.', $amount);
        // 将整数位的数值字符串拆分成数组
        $integerArr = str_split($amountArr[0], 1);
        
        // 将整数部分替换成大写汉字
        $result           = '人民币';
        $integerArrLength = count($integerArr);     // 整数位数组的长度
        $positionLength   = count($position);         // 单位数组的长度
        $zeroCount        = 0;                             // 连续为0数量
        for ($i = 0; $i < $integerArrLength; $i++) {
            // 如果数值不为0,则正常转换
            if ($integerArr[$i] != 0) {
                // 如果前面数字为0需要增加一个零
                if ($zeroCount >= 1) {
                    $result .= $digital[0];
                }
                $result    .= $digital[$integerArr[$i]] . $position[$positionLength - $integerArrLength + $i];
                $zeroCount = 0;
            } else {
                $zeroCount += 1;
                // 如果数值为0, 且单位是亿,万,元这三个的时候,则直接显示单位
                if (($positionLength - $integerArrLength + $i + 1) % 4 == 0) {
                    $result = $result . $position[$positionLength - $integerArrLength + $i];
                }
            }
        }
        
        // 如果小数位也要转换
        if ($type == 0) {
            // 将小数位的数值字符串拆分成数组
            
            if (!empty($amountArr[1])) {
                $decimalArr = str_split($amountArr[1], 1);
                
                // 将角替换成大写汉字. 如果为0,则不替换
                if ($decimalArr[0] != 0) {
                    $result = $result . $digital[$decimalArr[0]] . '角';
                }
                // 将分替换成大写汉字. 如果为0,则不替换
                if (!empty($decimalArr[1]) && $decimalArr[1] != 0) {
                    $result = $result . $digital[$decimalArr[1]] . '分';
                }
            } else {
                $result = $result . '整';
            }
            
        } else {
            $result = $result . '整';
        }
        
        
        return $result;
    }
    
    public static function order_for_payment($orders_id) {
        $main_payment         = 0;
        $agent_payment        = 0;
        $auditedAmount        = 0;//过审金额
        $rejectMoney          = 0;//驳回金额
        $main_paymentAudited  = 0;//主材过审金额
        $agent_paymentAudited = 0;//代购主材过审金额
        $toExamine            = 0;//待审核
        $payment_id           = 0;//待审核
        $io                   = db('payment')->where('orders_id', $orders_id)->order('payment_id ASC')->field('money,weixin,success,material,agency_material,cleared_time,to_examine,payment_id')->select();
        $orderSetting         = db('order_setting')->where('order_id', $orders_id)->value('payment_type');
        
        foreach ($io as $value) {
            //收款
            if ($value['weixin'] != 2 && $value['success'] != 3) {
                if ($orderSetting == 2) {
                    if ($value['agency_material'] == 0 && $value['material'] == 0) {
                        $main_payment += $value['money'];
                    }
                    if ($value['material'] != 0) {
                        $main_payment += $value['material'];
                    }
                    if ($value['agency_material'] != 0) {
                        $agent_payment += $value['agency_material'];
                    }
                } elseif ($orderSetting != 2) {
                    if (($value['weixin'] == 6 || $value['weixin'] == 8 || $value['weixin'] == 1) && !empty($value['cleared_time'])) {
                        if ($value['agency_material'] == 0 && $value['material'] == 0) {
                            $main_payment += $value['money'];
                        }
                        if ($value['material'] != 0) {
                            $main_payment += $value['material'];
                        }
                        if ($value['agency_material'] != 0) {
                            $agent_payment += $value['agency_material'];
                        }
                    }
                    if ($value['weixin'] != 6 && $value['weixin'] != 8 && $value['weixin'] != 1) {
                        if ($value['agency_material'] == 0 && $value['material'] == 0) {
                            $main_payment += $value['money'];
                        }
                        if ($value['material'] != 0) {
                            $main_payment += $value['material'];
                        }
                        if ($value['agency_material'] != 0) {
                            $agent_payment += $value['agency_material'];
                        }
                        
                        
                    }
                    
                }
                
            }
            if ($value['weixin'] == 2 && $value['success'] == 2) {
                if ($value['agency_material'] == 0 && $value['material'] == 0) {
                    $main_payment += $value['money'];
                }
                if ($value['material'] != 0) {
                    $main_payment += $value['material'];
                }
                if ($value['agency_material'] != 0) {
                    $agent_payment += $value['agency_material'];
                }
            }
            // 收款过审
            if ($value['weixin'] != 2 && !empty($value['cleared_time']) && $value['success'] != 3) {
                if ($value['agency_material'] == 0 && $value['material'] == 0) {
                    $auditedAmount += $value['money'];
                }
                if ($value['material'] != 0) {
                    $auditedAmount       += $value['material'];
                    $main_paymentAudited += $value['material'];
                }
                if ($value['agency_material'] != 0) {
                    $auditedAmount        += $value['agency_material'];
                    $agent_paymentAudited += $value['agency_material'];
                }
            }
            if ($value['weixin'] == 2 && $value['success'] == 2 && !empty($value['cleared_time'])) {
                if ($value['agency_material'] == 0 && $value['material'] == 0) {
                    $auditedAmount += $value['money'];
                }
                if ($value['material'] != 0) {
                    $auditedAmount       += $value['material'];
                    $main_paymentAudited += $value['material'];
                }
                if ($value['agency_material'] != 0) {
                    $auditedAmount        += $value['agency_material'];
                    $agent_paymentAudited += $value['agency_material'];
                }
            }
            if ($value['success'] == 3) {
                
                if ($orderSetting == 1) {
                    if ($value['agency_material'] == 0 && $value['material'] == 0) {
                        $rejectMoney += $value['money'];
                    }
                    if ($value['material'] != 0) {
                        $rejectMoney += $value['material'];
                    }
                    if ($value['agency_material'] != 0) {
                        $rejectMoney += $value['agency_material'];
                    }
                } elseif ($orderSetting == 2 && (($value['weixin'] == 6 || $value['weixin'] == 8 || $value['weixin'] == 1) && !empty($value['cleared_time']))) {
                    if ($value['agency_material'] == 0 && $value['material'] == 0) {
                        $rejectMoney += $value['money'];
                    }
                    if ($value['material'] != 0) {
                        $rejectMoney += $value['material'];
                    }
                    if ($value['agency_material'] != 0) {
                        $rejectMoney += $value['agency_material'];
                    }
                }
                
            }
            if ($value['to_examine'] == 2 && ($value['weixin'] == 6 || $value['weixin'] == 8 || $value['weixin'] == 1)) {
                $toExamine  = $value['money'];//待审核
                $payment_id = $value['payment_id'];//待审核
            }
            
        }
        
        return [$main_payment, $agent_payment, $auditedAmount, $rejectMoney, $main_paymentAudited, $agent_paymentAudited, $toExamine, $payment_id];
    }
    
    // 获取小数点后面的数字
    public function decimalPart($number) {
        
        $decimalPart = '';
        if (strpos($number, '.') !== false) {
            $decimalPart = substr($number, strpos($number, '.') + 1);
        }
        return "0." . $decimalPart;
    }
    
    /*
     * 车牌
     */
    public function licensePlate($cityId) {
        switch ($cityId) {
            case '241':
                $city_code = '川A';
                break;
            case '239':
                $city_code = '渝A';
                break;
            case '172':
                $city_code = '鄂A';
                break;
            case '262':
                $city_code = '贵A';
                break;
            case '375':
                $city_code = '沪A';
                break;
            case '202':
                $city_code = '粤B';
                break;
            case '501':
                $city_code = '京A';
                break;
            case '200':
                $city_code = '粤A';
                break;
            case '205':
                $city_code = '粤E';
            case '216':
                $city_code = '粤S';
            case '246':
                $city_code = '川B';
            default:
                $city_code = '';
                break;
            
        }
        return $city_code;
    }
    
    /*
   * 计算基建单价
   */
    public function newCapitalPrice($detailedOptionValue, $id, $getList,$fang=0) {
        
        $is_compose = db('detailed')->join('unit', 'unit.id=detailed.un_id', 'left')->where('detailed_id', $id)->field('detailed.artificial,detailed.pri,detailed.base_cost,detailed.base_labor_cost,unit.title,is_compose,warranty_years as warrantYears,warranty_text_1 as warrantyText1,warranty_text_2 as exoneration,detailed.groupss,small_order_fee,material_ratio,detailed.deleted_at,detailed.display,detailed.detailed_title,detailed.user_id,detailed.base_contract_price')->find();
        if(($is_compose['display'] ==0  || !empty($is_compose['deleted_at'])) && $is_compose['user_id']==0){
            return (['msg' =>  '【"'.$is_compose['detailed_title'].'"】为失效清单，无法提交报价，请删除后重试', 'code' => false,'products'=>'无法添加。此产品中【"'.$is_compose['detailed_title'].'"】清单/规格失效,请联系西蒙修改套餐']);
        }
        $detailed_option_value = db('detailed_option_value')->whereIn('option_value_id', $getList)->where(function ($quer) {
            $quer->whereNotNull('detailed_option_value.deleted_at')->whereOr('detailed_option_value.is_enable', '<>', 1);
        })->select();
        if(!empty($detailed_option_value)){
            return (['msg' => '【"'.$is_compose['detailed_title'].'-'.$detailed_option_value[0]['option_value_title'].'"】为失效规格，无法提交报价，请删除后重试', 'code' => false,'products'=>'无法添加。此产品中【"'.$detailed_option_value[0]['option_value_title'].'"】清单/规格失效,请联系西蒙修改套餐']);
        }
        if ($is_compose['is_compose'] == 1) {
            $list = $detailedOptionValue->where('detailed_option_value.detailed_id', $id)->join('detailed', 'detailed.detailed_id=detailed_option_value.detailed_id', 'left')->join('detailed_category', 'detailed.detailed_category_id=detailed_category.id', 'left')->join('unit', 'unit.id=detailed.un_id', 'left')->field('detailed.artificial as artificials,detailed.small_order_fee,detailed.agency,detailed.work_time as s,detailed.pri,detailed_option_value.*,unit.title,detailed_category.title as categoryTitle,detailed.warranty_years as warrantYears,detailed.warranty_text_1 as warrantyText1,detailed.warranty_text_2 as exoneration,detailed.agency,detailed_option_value.reimbursement,detailed.total_price,detailed.user_id as userId,detailed_option_value.extra_contract_price')->where('detailed_option_value.is_enable', 1)->whereNull('detailed_option_value.deleted_at')->select();
        } else {
            
            return (['data' => ['sum' => $is_compose['artificial'], 'price' => null, 'unit' => $is_compose['title'], 'categoryTitle' => '', 'sumTime' => 0, 'warrantYears' => $is_compose['warrantYears'], 'warrantyText1' => $is_compose['warrantyText1'], 'exoneration' => $is_compose['exoneration'], 'group' => $is_compose['groupss']], 'small_order_fee' => $is_compose['small_order_fee'], 'code' => true]);
        }
        
        if (empty($list)) {
            return (['msg' => '暂无基础报价', 'code' => false]);
        }
        
        $artificial      = $list[0]['artificials'];
        $pri             = $list[0]['pri'];
        $work_time       = $list[0]['s'];
        $base_contract_price=$is_compose['base_contract_price'];//发包基础价
        $base_labor_cost = $is_compose['base_labor_cost'];//基础工费
        $base_cost       = $is_compose['base_cost'];//基础成本
        $material_ratio       = $is_compose['material_ratio'];//材料比例(1表示1%)
        $conditionAdd    = [];
        $conditionRide   = [];
        $conditionMast   = [];
        $sum             = 0;
        $small_order_fee = null;
        //人工
        $sum1 = 0;
        //工时
        $sum2 = 0;
        $labor_cost_material=0;
        //公司提点
        $salesCommission=[];
        $salesNotCommission=[];
        //发包加价(元)
        $extra_contract_price=0;
        foreach ($list as $item) {
            if (!empty($getList)) {
                foreach ($getList as $value) {
                    if ($item['option_value_id'] == $value) {
                        if ($item['condition'] == 0) {
                            $conditionAdd[] = $item;
                        }
                        if ($item['condition'] == 1) {
                            $conditionRide[] = $item;
                        }
                        $base_labor_cost += $item['labor_cost'];
                        $base_cost       += $item['cost'];
                        $labor_cost_material +=$item['reimbursement'];
                        if($item['settlement_method'] >0 && $item['fixed_rate']>0){
                            $salesCommission[]=[
                                'settlement_method'=>$item['settlement_method'],
                                'fixed_rate'=>$item['fixed_rate'],
                                'fixed_cost'=>$item['fixed_cost'],
                            ];
                        }
                        if($item['settlement_method'] >1 ){
                            $salesNotCommission[]=[
                                'settlement_method'=>$item['settlement_method'],
                                'fixed_rate'=>$item['fixed_rate'],
                                'fixed_cost'=>$item['fixed_cost'],
                            ];
                        }
                       $extra_contract_price+= bcmul($item['extra_contract_price'],$fang,2);
                        
                    }
                    
                }
            }
            if ($item['condition'] == 2) {
                $conditionMast[] = $item;
            }
        }
        if(count($salesCommission)>1){
            return (['msg' => '清单结算配置有误，无法使用，请联系技术人员', 'code' => false]);
        }
        if(empty($salesCommission)){
            $salesCommission=$salesNotCommission;
        }
        if (!empty($is_compose['small_order_fee']) && $is_compose['small_order_fee'] != '[]') {
            $small_order_fee = json_decode($is_compose['small_order_fee'], true);
        }
        $price     = 0;
        $mastPrice = 0;
        $workTime  = 0;
        if (!empty($conditionAdd)) {
            $price     = array_sum(array_column($conditionAdd, 'price'));
            $mastPrice = array_sum(array_column($conditionAdd, 'artificial'));
            $workTime  = array_sum(array_column($conditionAdd, 'work_time'));
            
        }
      
        //单价
        $AddPrice = $price + $artificial;
        //人工
        $AddArtificial = $mastPrice + $pri;
        //工时
        $AddWorkTime = $workTime + $work_time;
        
        if (!empty($conditionRide)) {
            $RidePrice      = array_column($conditionRide, 'price');
            $RideArtificial = array_column($conditionRide, 'artificial');
            $RideWorkTime   = array_column($conditionRide, 'work_time');
            
            for ($i = 0; $i < count($RidePrice); $i++) {
                if ($sum == 0) {
                    $sum = $AddPrice * $RidePrice[$i];
                } else {
                    $sum = $sum * $RidePrice[$i];
                }
                
            }
            for ($i = 0; $i < count($RideArtificial); $i++) {
                if ($sum1 == 0) {
                    $sum1 = $AddArtificial * $RideArtificial[$i];
                } else {
                    $sum1 = $sum1 * $RideArtificial[$i];
                }
            }
            for ($i = 0; $i < count($RideWorkTime); $i++) {
                if ($sum2 == 0) {
                    $sum2 = $AddWorkTime * $RideWorkTime[$i];
                } else {
                    $sum2 = $sum2 * $RideWorkTime[$i];
                }
            }
        } else {
            $sum  = $AddPrice;
            $sum1 = $AddArtificial;
            $sum2 = $AddWorkTime;
        }
        
        $configure['price']      = !empty($conditionMast) ? json_decode($conditionMast[0]['price']) : [];
        $configure['artificial'] = !empty($conditionMast) ? json_decode($conditionMast[0]['artificial']) : [];
        $configure['work_time']  = !empty($conditionMast) ? json_decode($conditionMast[0]['work_time']) : [];
        $configure['sum']        = $sum;
        $configure['sumMast']    = $sum1;
        if ($list[0]['agency'] == 1) {
            $configure['sumMast'] = $base_labor_cost;
        }
        
        $configure['sumTime']         = $sum2;
        $configure['base_cost']       = $base_cost;
        $configure['base_contract_price']=bcadd($base_contract_price,$extra_contract_price,2);
        $configure['unit']            = $list[0]['title'];
        $configure['categoryTitle']   = $list[0]['categoryTitle'];
        $configure['warrantYears']    = $list[0]['warrantYears'];
        $configure['warrantyText1']   = $list[0]['warrantyText1'];
        $configure['exoneration']     = $list[0]['exoneration'];
        $configure['material_ratio']     =$material_ratio;
        $configure['labor_cost_material']     = $labor_cost_material;
        $configure['group']           = $is_compose['groupss'];
        $configure['small_order_fee'] = $small_order_fee;
        $configure['total_price'] = $list[0]['total_price'];
        $configure['userId'] = $list[0]['userId'];
        $configure['salesCommission'] = $salesCommission;
        return ['code' => true, 'data' => $configure];
    }
    
    /**
     * 获取微信用户端小程序码
     * @param $params
     * @return string
     */
    public function getCodeUser($type = 1) {
        $redis = new RedisPackage();
        $redis::select(1);
        header('content-type:text/html;charset=utf-8');
        $ACCESS_TOKEN = '';
        if (config('app_dev') == 'dev') {
            $APP_ID     = config('OM.appid');
            $APP_SECRET = config('OM.AppSecret');
            if ($type == 2) {
                $redis::del('gowechat_miniprogram__access_token_' . $APP_ID);
            }
            if ($redis::get('gowechat_miniprogram__access_token_' . $APP_ID)) {
                $ACCESS_TOKEN = $redis::get('gowechat_miniprogram__access_token_' . $APP_ID);
            }
        } else {
            $APP_ID     = config('ClientApplets.appid');
            $APP_SECRET = config('ClientApplets.AppSecret');
            if ($type == 2) {
                $redis::del('gowechat_miniprogram__access_token_' . $APP_ID);
            }
            if ($redis::get('gowechat_miniprogram__access_token_' . $APP_ID)) {
                $ACCESS_TOKEN = $redis::get('gowechat_miniprogram__access_token_' . $APP_ID);
            }
        }
        if (empty($ACCESS_TOKEN)) {
            $o            = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $APP_ID . '&secret=' . $APP_SECRET;
            $result       = send_post($o, [], 0);
            $result       = json_decode($result, true);
            $ACCESS_TOKEN = $result['access_token'];
            $redis::set('gowechat_miniprogram__access_token_' . $APP_ID, $ACCESS_TOKEN, 7200);
        }
        return $ACCESS_TOKEN;
    }
    
    /*
     * 店长端获取推客二维码
     */
    public function personalName($user, $cityId, $type = 1) {
        
        $ACCESS_TOKEN = $this->getCode();
        $personal     = \db('personal')->where('mobile', $user['mobile'])->where('city_id', config('cityId'))->find();
        if (empty($personal)) {
            $n           = $this->getGrouping($type, $cityId);
            $personal_id = \db('personal')->insertGetId(['mobile' => $user['mobile'], 'username' => $user['username'], 'avatar' => 'https://images.yiniao.co/tuikebaohe/tx.png', 'sex' => 1, 'status' => 0, 'created_time' => time(), 'num' => $n, 'group_id' => '', 'city_id' => config('cityId')]);
            \db('personal', config('database.zong'))->insert(['personal_id' => $personal_id, 'mobile' => $user['mobile'], 'username' => $user['username'], 'avatar' => 'https://images.yiniao.co/tuikebaohe/tx.png', 'sex' => 1, 'status' => 0, 'created_time' => time(), 'num' => $n, 'group_id' => '', 'city_id' => config('cityId')]);
            $personal['personal_id'] = $personal_id;
        }
        $qr_code = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $ACCESS_TOKEN;
        //sourceType 1推客宝盒2店长3师傅
        $params = ['scene' => 'st=2&num=sn11&id=' . enPersonalId($personal['personal_id']) . '&cheng=' . config('city'), "width" => 230, 'page' => 'pages/login/newLogin'];
        if ($type == 2) {
            $params = ['scene' => 'st=3&num=sn11&id=' . enPersonalId($personal['personal_id']) . '&cheng=' . config('city'), "width" => 230, 'page' => 'pages/login/newLogin'];
        }
        $changed    = json_encode($params);
        $result     = send_post($qr_code, $changed, 1);
        $Aliyun     = new Aliyunoss();
        $oss_result = $Aliyun->putStr('appQrCode/' . $params['scene'] . '.png', $result);
        if ($oss_result['info']['http_code'] == 200) {
            $paths = parse_url($oss_result['info']['url'])['path'];
        }
        $src               = 'https://images.yiniao.co' . $paths . '?t=' . time();
        $todayData         = [];
        $personal_share    = db('personal_share')->where('personal_share.referencesss', $personal['personal_id'])->field('personal_share.created_time')->select();
        $personal_username = db('personal_share')->Join('personal', 'personal.personal_id=personal_share.referencesss', 'left')->where('personal_share.register', $personal['personal_id'])->value('personal.mobile');
        foreach ($personal_share as $t) {
            $start_time = strtotime(date("Y-m-d", time()));
            $end_time   = $start_time + 60 * 60 * 24;
            // 使用IF当作字符串判断是否相等
            if ($start_time < $t['created_time'] && $end_time > $t['created_time']) {
                $todayData[] = $t;
            }
        }
        
        return ['src' => $src, 'personalShare' => count($personal_share), 'todayData' => count($todayData), 'personal_username' => $personal_username];
    }
    
    /**
     * 获取微信推客宝盒小程序码
     * @param $params
     * @return string
     */
    public function getCode() {
        $redis = new RedisPackage();
        $redis::select(1);
        header('content-type:text/html;charset=utf-8');
        $APP_ID     = 'wxab9895c4ac9ed7f1';
        $APP_SECRET = 'cb629244173b11ee42cd00a0ebcd9eea';
        if ($redis::get('gowechat_miniprogram__access_token_' . $APP_ID)) {
            $ACCESS_TOKEN = $redis::get('gowechat_miniprogram__access_token_' . $APP_ID);
        } else {
            $o            = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $APP_ID . '&secret=' . $APP_SECRET;
            $result       = send_post($o, [], 0);
            $result       = json_decode($result, true);
            $ACCESS_TOKEN = $result['access_token'];
            $redis::set('gowechat_miniprogram__access_token_' . $APP_ID, $ACCESS_TOKEN, 7200);
        }
        return $ACCESS_TOKEN;
    }
    
    public function array_to_json($array) {
        foreach ($array as $k => &$v) {
            if (is_array($v)) {
                foreach ($v as $k1 => &$v1) {
                    if (is_array($v1)) {
                        foreach ($v1 as $k2 => &$v2) {
                            if (is_array($v2)) {
                                foreach ($v2 as $k3 => &$v3) {
                                    if (is_array($v3)) {
                                        foreach ($v3 as $k4 => &$v4) {
                                            $v3[$k4] = (is_string($v4)) ? urlencode($v4) : $v4;
                                        }
                                    } else {
                                        $v2[$k3] = (is_string($v3)) ? urlencode($v3) : $v3;
                                    }
                                }
                            } else {
                                $v1[$k2] = (is_string($v2)) ? urlencode($v2) : $v2;
                            }
                        }
                    } else {
                        $v[$k1] = (is_string($v1)) ? urlencode($v1) : $v1;
                    }
                }
                // $this->array_to_json($v);
            } else {
                $array[$k] = (is_string($v)) ? urlencode($v) : $v;
            }
        }
        return urldecode(json_encode($array, JSON_UNESCAPED_UNICODE));
    }
    
    /*
     * 下单成功通知
     */
    public function SuccessfulSigning($openid, $amount, $orderNo, $deal) {
        $a = ["touser" => $openid, "template_id" => "froefTcZqLF4qmryk-uU7i1xKam_2AzFZI6-yAMDLTQ", "page" => '/pages/home/home', "lang" => "zh_CN", "data" => ['character_string1' => ["value" => $orderNo,], 'amount3' => ["value" => $amount,],
            
            'thing4' => ["value" => "预计成交佣金{$deal}元",],
        
        
        ]];
        
        return json_encode($a, JSON_UNESCAPED_UNICODE);
        
    }
    
    /*
     * 门店维修通知
     */
    public function StoreMaintenance($openid, $planned, $orderNo, $commission) {
        $a = ["touser" => $openid, "template_id" => "QrPVdjIprgNb3w6eUaWLulVM-QQsLesCl1VJKhAviGs", "page" => '/pages/home/moneydetail', "lang" => "zh_CN", "data" => ['character_string1' => ["value" => $orderNo,], 'time4' => ["value" => $planned,],
            
            'thing5' => ["value" => "预计上门佣金{$commission}元",],
        
        ],];
        
        return json_encode($a, JSON_UNESCAPED_UNICODE);
        
    }
    
    /*
     * 审核拒绝
     */
    public function approvalReminder($data) {
        
        db('approval_info', config('database.zong'))->insert($data);
    }
    
    /*
         * app提成奖励
         */
    public function award_config_rule($order_id, $orderModel, $type) {
        $us = db('order', config('database.zong'))->field('order.pro_id,order.channel_details,order.entry_type,order.entry_user_id,order.tui_jian,order.hematopoiesis,order.created_time')->where('order_id', $order_id)->find();
        if (!empty($us['tui_jian']) || $us['hematopoiesis'] == 0) {
            return true;
        }
        if ($us['entry_type'] == 1) {
//            $us['store_id'] = \db('user', config('database.zong'))->where('user_id', $us['entry_user_id'])->value('store_id');
            $role = 1;
        } elseif ($us['entry_type'] == 2) {
//            $us['store_id'] = \db('app_user', config('database.zong'))->where('id', $us['entry_user_id'])->value('store_id');
            $role = 2;
        }
        
        if ($us['entry_user_id'] != 0 && !empty($us['entry_user_id'])) {
            $award_config = db('award_config_store', config('database.zong'))->field('award_config_rule.award_rule_2,award_config_rule.award_rule_1,award_config_rule.id,award_config_store.award_id')->join('award_config_rule', 'award_config_rule.award_id=award_config_store.award_id', 'left')->join('award_config', 'award_config_rule.award_id=award_config.id', 'left')->where(['award_config_rule.goods_category_id' => $us['pro_id']])->where('find_in_set(:id,award_config_channel_details)', ['id' => $us['channel_details']])->where('award_record_role', $role)->find();
            $deal         = 0;
            $commission   = 0;
            if (1725379200 <= $us['created_time'] ) {
                $SingleSettlement= $orderModel->SingleSettlement($order_id);
                $amount=$SingleSettlement['agencyMoney']+$SingleSettlement['MainMaterialMoney'];
            }else{
                $amount = $orderModel->TuiNewOffer($order_id)['amount'];
            }
            if (!empty($award_config)) {
                if (1652065582 > $us['created_time']) {
                    $award_config = ['award_rule_2' => 3, 'award_rule_1' => 5000, 'award_id' => $award_config['award_id']];
                    
                }
                if (1652065582 <= $us['created_time'] && $us['created_time'] <= 1675958400) {
                    $award_config = ['award_rule_2' => 4, 'award_rule_1' => 0, 'award_id' => $award_config['award_id']];
                }
                if (1725379200 <= $us['created_time'] ) {
                    $award_config = ['award_rule_2' => 5, 'award_rule_1' => 0, 'award_id' => $award_config['award_id']];
                }
                $deal       += $amount * ($award_config['award_rule_2'] / 100);
                $commission += ($award_config['award_rule_1'] / 100);
                if ($commission != 0) {
                    $my_order_award = db('my_order_award', config('database.zong'))->where(['order_id' => $order_id, 'user_id' => $us['entry_user_id'], 'type' => $us['entry_type'], 'commission' => $commission])->find();
                    if (empty($my_order_award)) {
                        $profit    = $commission;
                        $length    = 1;//默认一条
                        $remainder = 0;//余数金额
                        if ($profit > 0) {
                            //拆分条数
                            $length = ceil($profit / 200);
                            //余数金额
                            $remainder = round((floatval($profit) - (($length - 1) * 200)), 2);
                        }
                        
                        for ($i = 0; $i < $length; $i++) {
                            $profit = 200;
                            $x      = $i + 1;
                            if ($x == $length) {
                                $profit = $remainder;//余数
                            }
                            $myOrderAwardId = db('my_order_award', config('database.zong'))->insertGetId(['user_id' => $us['entry_user_id'], 'type' => $us['entry_type'], 'grade' => $award_config['award_id'], 'order_id' => $order_id, 'deal' => 0, 'uptime' => time(), 'profit' => round($profit, 2), 'commission' => round($profit, 2), 'state' => 1, 'remarks' => "原价：" . $commission . "拆分条数" . $length, 'award_rule_1' => $award_config['award_rule_1'], 'award_rule_2' => $award_config['award_rule_2'],]);
                            Db::connect(config('database.zong'))->table('my_order_withdrawal')->insert(['user_id' => $us['entry_user_id'], 'type' => $us['entry_type'], 'amount' => round($profit, 2), 'crtime' => time(), 'start' => 1, 'my_order_award_id' => $myOrderAwardId,]);
                        }
                        
                    }
                }
                if ($deal != 0) {
                    $my_order_award1 = db('my_order_award', config('database.zong'))->where(['order_id' => $order_id, 'user_id' => $us['entry_user_id'], 'type' => $us['entry_type'], 'deal' => $deal])->order('id desc')->find();
                    if (empty($my_order_award1)) {
                        $profitDeal    = $deal;
                        $lengthDeal    = 1;//默认一条
                        $remainderDeal = 0;//余数金额
                        if ($profitDeal > 0) {
                            //拆分条数
                            $lengthDeal = ceil($profitDeal / 200);
                            //余数金额
                            $remainderDeal = round((floatval($profitDeal) - (($lengthDeal - 1) * 200)), 2);
                        }
                        
                        for ($i = 0; $i < $lengthDeal; $i++) {
                            $profitDeal = 200;
                            $x          = $i + 1;
                            if ($x == $lengthDeal) {
                                $profitDeal = $remainderDeal;//余数
                            }
                            $myOrderAwardId2 = db('my_order_award', config('database.zong'))->insertGetId(['user_id' => $us['entry_user_id'], 'type' => $us['entry_type'], 'grade' => $award_config['award_id'], 'order_id' => $order_id, 'deal' => round($profitDeal, 2), 'uptime' => time(), 'profit' => round($profitDeal, 2), 'commission' => 0, 'state' => 1, 'remarks' => "原价：" . $deal . "拆分条数" . $lengthDeal, 'award_rule_1' => $award_config['award_rule_1'], 'award_rule_2' => $award_config['award_rule_2'],]);
                            Db::connect(config('database.zong'))->table('my_order_withdrawal')->insert(['user_id' => $us['entry_user_id'], 'type' => $us['entry_type'], 'amount' => round($profitDeal, 2), 'crtime' => time(), 'start' => 1, 'my_order_award_id' => $myOrderAwardId2,]);
                        }
                        
                    }
                }
            }
        }
        
        
    }

    /*
     * 推客宝上门佣金奖励
     */
    public function CommissionCalculation($order_id, $orderModel, $type = 2, $huo = 0)
    {
        $ti = 0;
        $us = db('order')->field('order.ification,order.telephone,order.order_no,order.planned,order.pro_id2,order.tui_jian,order.tui_role,order.pro_id')->where('order_id', $order_id)->find();
        if (empty($us['tui_jian'])) {
            Db::connect(config('database.zong'))->table('tukebao_audit_log')->insert(['order_id' => $order_id, 'income_id' => $type, 'state' => 0, 'personal_id' => $us['tui_jian'], 'created_time' => time(), 'reason' => "没有推荐人tui_jian为空",]);
            return true;
        }
        $personal  = db('personal', config('database.zong'))->where(['status' => 0, 'personal_id' => $us['tui_jian']])->find();
        $shopowner = self::city($personal['city_id']);
        if (empty($shopowner)) {
            Db::connect(config('database.zong'))->table('tukebao_audit_log')->insert(['order_id' => $order_id, 'income_id' => $type, 'state' => 0, 'personal_id' => $us['tui_jian'], 'created_time' => time(), 'reason' => "城市获取错误",]);
            return true;
        }
        $deal             = 0;
        $group_proportion = 0;
        $commission       = 0;
        $amount           = $orderModel->TuiNewOffer($order_id)['amount'];
        if ($personal['group'] == 0 && $personal['num'] != 0) {
            $ti = db('ti', config('database.zong'))->where(['goods_category_id' => $us['pro_id'], 'personal_id' => $personal['num']])->find();
        } elseif ($personal['group'] == 0 && $personal['num'] == 0) {
            $ti = db('ti', config('database.zong'))->where(['goods_category_id' => $us['pro_id'], 'single' => $personal['personal_id']])->find();
        }
        $redis = new RedisPackage();
        $tt    = $redis::setnx(md5($order_id . $us['tui_jian']), $order_id . $us['tui_jian']); //操作之前进行redis赋值操作
        if (!$tt) {
            Db::connect(config('database.zong'))->table('tukebao_audit_log')->insert(['order_id' => $order_id, 'income_id' => 0, 'state' => 0, 'personal_id' => $us['tui_jian'], 'created_time' => time(), 'reason' => "奖励已存在",]);
            $redis::del(md5($order_id . $us['tui_jian']));
            return true;
        }
        DB::connect(config('database.' . $shopowner['db']))->table('income')->startTrans();

        try {

            if (!empty($ti)) {
                if ($personal['group'] == 0 && $personal['num'] != 0) {
                    $deal             += $amount * $ti['bi'];
                    $group_proportion += $amount * $ti['group_proportion'];
                    $commission       += $ti['yong'];
                }
                if ($personal['group'] == 0 && $personal['num'] == 0) {
                    $deal       += $amount * $ti['personal'];
                    $commission += $ti['commission'];
                }

                if ($type == 1 && $commission != 0) {
                    $io     = DB::connect(config('database.' . $shopowner['db']))->table('income')->lock(true)->where(['order_id' => $order_id, 'personal_id' => $us['tui_jian'], 'mode' => '上门奖励'])->find();
                    $income = empty($io['income_id']) ? 0 : $io['income_id'];
                    if (empty($io)) {
                        $income = DB::connect(config('database.' . $shopowner['db']))->table('income')->insertGetId(['personal_id' => $us['tui_jian'], 'profit' => $commission, 'commission' => $commission, 'uptime' => time(), 'order_id' => $order_id, 'mode' => '上门奖励']);
                    } else {
                        $income =  $io['income_id'];
                    }

                    //                    if ($income ) {
                    //                        if (preg_match("/^1[345678]{1}\d{9}$/", $personal['mobile'])) {
                    //                            sendMsg($personal['mobile'], 243403, [$us['order_no'], $commission]);
                    //                        }
                    //                        $d = json_decode($this->StoreMaintenance($personal['openid'], $us['planned'], $us['order_no'], $commission), true);
                    //                        $o=send_post('https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $this->getCode(), $this->array_to_json($d), 1);
                    //                    }
                    $toExamine = $income;
                }
                if ($type == 2 && $deal != 0) {
                    $iop     = DB::connect(config('database.' . $shopowner['db']))->table('income')->lock(true)->where(['order_id' => $order_id, 'personal_id' => $us['tui_jian'], 'mode' => '成交提成'])->find();
                    $income2 = empty($iop['income_id']) ? 0 : $iop['income_id'];
                    if (empty($iop)) {
                        $income2 = DB::connect(config('database.' . $shopowner['db']))->table('income')->insertGetId(['personal_id' => $us['tui_jian'], 'group_proportion' => $group_proportion, 'deal' => $deal, 'profit' => $deal, 'uptime' => time(), 'order_id' => $order_id, 'mode' => '成交提成']);
                    }

                    //
                    //                    if ($income2 && $income4) {
                    //                        if (preg_match("/^1[345678]{1}\d{9}$/", $personal['mobile'])) {
                    //                            sendMsg($personal['mobile'], 243404, [$us['order_no'], $deal]);
                    //                        }
                    //                        $d1 = json_decode($this->SuccessfulSigning($personal['openid'], $amount, $us['order_no'], $deal), true);
                    //                        send_post('https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $this->getCode(), $this->array_to_json($d1), 1);
                    //                    }
                    $toExamine = $income2;
                }
                //跟报价没有关系
                if ($huo == 3 && (($ti['personal'] != 0 || $ti['commission'] != 0) || ( $ti['yong']  != 0 || $ti['bi']  != 0))) {
                    $personal_activity_rewards = db('personal_activity_rewards', config('database.zong'))->where('status', 1)->find();
                    $personal_activity_rewards_log_order_id = db('personal_activity_rewards_log', config('database.zong'))->where('personal_id', $us['tui_jian'])->where('activity_id', $personal_activity_rewards['id'])->column('order_id');
                    $orderCount = db('order')->join('order_times', 'order_times.order_id=order.order_id', 'left')->where('order_times.first_clock_time', '>', 0)->whereBetween('order.created_time', [$personal_activity_rewards['start_time'], $personal_activity_rewards['end_time']])->where('order.tui_jian',$us['tui_jian'])->where('order.tui_role',2)->whereNotIn('order.order_id', $personal_activity_rewards_log_order_id)->limit(3)->column('order.order_id');
                    if (count($orderCount) >= $personal_activity_rewards['condition'] && $personal_activity_rewards['type'] == 1) {
                        $io1    = DB::connect(config('database.' . $shopowner['db']))->table('income')->lock(true)->where(['order_id' => $order_id, 'personal_id' => $us['tui_jian'], 'mode' => '活动加码奖励'])->find();
                        $incomeList = ['personal_id' => $us['tui_jian'], 'profit' => $personal_activity_rewards['reward_money'], 'commission' => $personal_activity_rewards['reward_money'], 'uptime' => time(), 'order_id' => $order_id, 'mode' => '活动加码奖励','state'=>1];
                        if (empty($io1)) {
                            $income = DB::connect(config('database.' . $shopowner['db']))->table('income')->insertGetId($incomeList);
                            foreach ($orderCount as  $vale) {
                                db('personal_activity_rewards_log', config('database.zong'))->insert(['income_id' => $income, 'order_id' => $vale, 'create_time' => time(), 'personal_id' => $us['tui_jian'], 'activity_id' => $personal_activity_rewards['id']]);
                            }
                            $examineList = ['personal_id' => $incomeList['personal_id'], 'qian' => $incomeList['commission'], 'mode' => $incomeList['mode'], 'crtime' => time(), 'start' => 2, 'income_id' => $income, 'personal_ids' => 0, 'before' => 2];
                            DB::connect(config('database.' . $shopowner['db']))->table('examine')->insertGetId($examineList);
                           
                        }
                    }
                }
            }

            DB::connect(config('database.' . $shopowner['db']))->table('income')->commit();
            $redis::del(md5($order_id . $us['tui_jian']));
             sleep(1);
            $order_times = db('order_times')->where('order_id', $order_id)->find();
           if (isset($toExamine) && !empty($toExamine)) {
                if (($order_times['first_clock_time'] != 0 && $order_times['envelopes_first_time'] != 0) || ($order_times['first_clock_time'] != 0 && $order_times['first_through_time'] != 0) || $type == 2) {
                    $this->toExamine($toExamine, $order_id, 1, '');
                }
            }
            
        } catch (\Exception $e) {
            $redis::del(md5($order_id . $us['tui_jian']));
            DB::connect(config('database.' . $shopowner['db']))->table('income')->rollback();
        }
    }
    
    public function supply($id) {
        $business_id = db('agency_business', config('database.zong'))->where('agency_id', $id)->column('business_id');
        $agency_business      = db('agency_business_config', config('database.zong'));
        if($id !=0){
            $value=$agency_business ->whereIn('id', $business_id)->column('value');
        }else{
            $value=$agency_business->field('value as title,id')->select();
            
        }
        if($id !=0) {
            return empty($value) ? '' : implode($value, ',');
        }else{
            return empty($value) ? null : $value;
        }
        
    }
    
    /*
     * 判断是不是贝壳
     */
    
    public function keyAccount($id) {
        $shell       = Db::connect(config('database.zong'))->table('sys_config')->where('keyss', 'key_account')->value('valuess');//(贝壳渠道，采用线下纸质合同和线下支付)
        $isNeedPaper = Db::connect(config('database.zong'))->table('sys_config')->where('keyss', 'key_account_supplement')->value('valuess');//采用电子合同与线上支付
        $shell       = explode(',', $shell);
        $isNeedPaper = explode(',', $isNeedPaper);
        $account     = [];
        foreach ($shell as $k => $item) {
            foreach ($isNeedPaper as $value) {
                if ($item != $value) {
                    $account[] = $item;
                }
                
            }
            
        }
        return ['shell' => in_array($id, $shell) ? 1 : 0, 'isNeedPaper' => in_array($id, $account) ? 1 : 0];
        
        
    }
    
    public function SupplierType() {
        $data = [['title' => '主材供应商', 'id' => 1]];
        return $data;
        
        
    }
    
    /*
     * u8c
     */
    public function U8c($orderID, $type) {
        
        $content    = '';
        $sum        = 0;
        $appCapital = 0;
        if ($type == 11) {
            $appCapital = Db::connect(config('database.db2'))->table('app_user_order_capital')->join('app_user', 'app_user.id=app_user_order_capital.user_id', 'left')->join(config('database.database') . '.store', 'store.store_id=app_user.store_id', 'left')->join(config('database.database') . '.order', 'order.order_id=app_user_order_capital.order_id', 'left')->join(config('database.database') . '.capital', 'capital.capital_id=app_user_order_capital.capital_id', 'left')->where(['order.order_id' => $orderID])->where(['capital.types' => 1, 'types' => 1, 'enable' => 1])->whereNull('app_user_order_capital.deleted_at')->field('app_user.username,store.store_name,order.addres,sum(app_user_order_capital.personal_price) as personal_price')->group('app_user_order_capital.user_id')->select();
            if (!empty($appCapital)) {
                $content = $appCapital[0]['store_name'] . '师傅提成:';
                foreach ($appCapital as $item) {
                    $content .= $item['addres'] . '--' . $item['username'] . '(' . $item['personal_price'] . ');';
                }
                $sum = array_sum(array_column($appCapital, 'personal_price'));
            }
        } elseif ($type == 12) {
            $appCapital = $_reimbursement = db('reimbursement')->join(config('database.db2')['database'] . '.app_user', 'app_user.id=reimbursement.user_id', 'left')->join('user', 'user.user_id=reimbursement.user_id', 'left')->join('store', 'store.store_id=app_user.store_id', 'left')->join('order', 'order.order_id=reimbursement.order_id', 'left')->where(['reimbursement.order_id' => $orderID, 'reimbursement.status' => 1, 'reimbursement.classification' => ['<>', 4]])->field('if(reimbursement.type=2,app_user.username,user.username) as username,store.store_name,order.addres,sum(reimbursement.money) as money,if(reimbursement.type=2,"师傅","店长") as classification')->group('reimbursement.user_id,reimbursement.type')->select();
            if (!empty($appCapital)) {
                $content = $appCapital[0]['store_name'] . '--' . $appCapital[0]['addres'] . '报销详情:';
                foreach ($appCapital as $item) {
                    $content .= '(' . $item['classification'] . ')' . $item['username'] . '(' . $item['money'] . ');';
                }
                $sum = array_sum(array_column($appCapital, 'money'));
            }
        } elseif ($type == 14) {
            $appCapital = $_reimbursement = db('reimbursement')->join(config('database.db2')['database'] . '.app_user', 'app_user.id=reimbursement.user_id', 'left')->join('user', 'user.user_id=reimbursement.user_id', 'left')->join('store', 'store.store_id=app_user.store_id', 'left')->join('order', 'order.order_id=reimbursement.order_id', 'left')->where(['reimbursement.order_id' => $orderID, 'reimbursement.status' => 1, 'reimbursement.classification' => 4])->field('if(reimbursement.type=2,app_user.username,user.username) as username,store.store_name,order.addres,sum(reimbursement.money) as money,if(reimbursement.type=2,"师傅","店长") as classification')->group('reimbursement.user_id,reimbursement.type')->select();
            if (!empty($appCapital)) {
                $content = $appCapital[0]['store_name'] . '--' . $appCapital[0]['addres'] . '报销详情:';
                foreach ($appCapital as $item) {
                    $content .= '(' . $item['classification'] . ')' . $item['username'] . '(' . $item['money'] . ');';
                }
                $sum = array_sum(array_column($appCapital, 'money'));
            }
        }
        if (!empty($appCapital)) {
            return U8cMasters($content, $sum, $orderID, $type);
            
        }
        
    }
    
    /*
     * 佣金审核
     */
    public function toExamine($toExamineId, $order_id, $state, $reason) {
        $shopowner = self::city($order_id);
        if (empty($shopowner)) {
            Db::connect(config('database.zong'))->table('tukebao_audit_log')->insert(['order_id' => $order_id, 'income_id' => $toExamineId, 'state' => 0, 'personal_id' => '', 'created_time' => time(), 'reason' => "城市获取错误",]);
            return true;
        }
        $redis = new RedisPackage();
        $tt    = $redis::setnx(md5($order_id . $toExamineId), $order_id . $toExamineId);//操作之前进行redis赋值操作
        if (!$tt) {
            Db::connect(config('database.zong'))->table('tukebao_audit_log')->insert(['order_id' => $order_id, 'income_id' => $toExamineId, 'state' => 0, 'personal_id' => 0, 'created_time' => time(), 'reason' => "奖励生成防重复",]);
            $redis::del(md5($order_id . $toExamineId));
            return true;
        }
        $Door['personal_id'] = 0;
        DB::connect(config('database.' . $shopowner['db']))->table('income')->startTrans();
        DB::connect(config('database.' . $shopowner['db']))->table('examine')->startTrans();
        try {
            if ($toExamineId != 0) {
                $rewardMoney = DB::connect(config('database.zong'))->table('income')->lock(true)->where('income_id', $toExamineId)->where('state', 1)->select();
                if (!empty($rewardMoney)) {
                    throw new Exception('奖励已通过');
                }
                $Door    = DB::connect(config('database.zong'))->table('income')->lock(true)->where('income_id', $toExamineId)->find();
                $examine = DB::connect(config('database.' . $shopowner['db']))->lock(true)->table('examine')->where('income_id', $toExamineId)->find();
                if (!empty($Door) && $state == 1 && empty($examine) && $Door['state'] == 0) {
                    $profit    = $Door['profit'];
                    $length    = 1;//默认一条
                    $remainder = 0;//余数金额
                    if ($profit > 0) {
                        //拆分条数
                        $length = ceil($profit / 200);
                        //余数金额
                        $remainder = round((floatval($profit) - (($length - 1) * 200)), 2);
                    }
                   
                    for ($i = 0; $i < $length; $i++) {
                        $profit = 200;
                        $x      = $i + 1;
                        if ($x == $length) {
                            $profit = $remainder;//余数
                        }
                        DB::connect(config('database.' . $shopowner['db']))->table('examine')->insertGetId(['personal_id' => $Door['personal_id'], 'qian' => $profit, 'mode' => $Door['mode'], 'crtime' => time(), 'start' => 2, 'income_id' => $toExamineId, 'personal_ids' => 0, 'before' => 2,]);
                       
                    }
                    DB::connect(config('database.' . $shopowner['db']))->table('income')->where('income_id', '=', $toExamineId)->update(['admin_id' => 86,  'state' => $state, 'reason' =>'']);
                    Db::connect(config('database.zong'))->table('tukebao_audit_log')->insert(['order_id' => $order_id, 'income_id' => $toExamineId, 'state' => $state, 'personal_id' => $Door['personal_id'], 'created_time' => time(), 'reason' => "生成奖励成功",]);
                }
                
            }
            
            DB::connect(config('database.' . $shopowner['db']))->table('income')->commit();
            DB::connect(config('database.' . $shopowner['db']))->table('examine')->commit();
           
            $redis::del(md5($order_id . $toExamineId));
        } catch (Exception $e) {
            DB::connect(config('database.' . $shopowner['db']))->table('income')->rollback();
            DB::connect(config('database.' . $shopowner['db']))->table('examine')->rollback();
            Db::connect(config('database.zong'))->table('tukebao_audit_log')->insert(['order_id' => $order_id, 'income_id' => $toExamineId, 'state' => $state, 'personal_id' => $Door['personal_id'], 'created_time' => time(), 'reason' => $e->getMessage(),]);
            $redis::del(md5($order_id . $toExamineId));
            
        }
        
    }
    
    /*
    * 获取城市
    */
    public function obtainCity($cityName = '', $type = 1) {
        $city_id = db('city');
        if ($cityName != '') {
            $city_id->where(['city' => ['like', "%{$cityName}%"]]);
        }
        if (config('city') == 'cd') {
            $exp = new \think\db\Expression('field(city_id,241,239,262,172,375,202,501)');
        } elseif (config('city') == 'wh') {
            $exp = new \think\db\Expression('field(city_id,172,241,239,262,375,202,501)');
        } elseif (config('city') == 'gy') {
            $exp = new \think\db\Expression('field(city_id,262,241,239,172,375,202,501)');
        } elseif (config('city') == 'cq') {
            $exp = new \think\db\Expression('field(city_id,239,241,262,172,375,202,501)');
        } else {
            $exp = new \think\db\Expression('field(city_id,241,239,262,172,375,202,501)');
        }
        
        if ($type == 2) {
            $city_id->where('city_id', 'in', [241, 239, 262, 172, 375, 202, 501]);
        }
        $list = $city_id->field('city_id as id,city as title')->order($exp)->select();
        return $list;
    }
    
    /*
    * 户型
    */
    public function HouseData() {
        
        return [['id' => 1, 'title' => '一居室'], ['id' => 2, 'title' => '二居室'], ['id' => 3, 'title' => '三居室'], ['id' => 4, 'title' => '四居室'], ['id' => 5, 'title' => '跃层'], ['id' => 6, 'title' => '复式'], ['id' => 7, 'title' => '别墅'], ['id' => 8, 'title' => '其它'], ['id' => 9, 'title' => '不限户型']];
    }
    
    public function encryption($store_id) {
        $company_id = db('company_config', config('database.zong'))->where('company_id', $store_id)->where('status', 1)->find();
        
        $cusid  = $company_id['allpay_cusid'];
        $key    = $company_id['allpay_key'];
        $APP_ID = $company_id['allpay_appid'];
        return [$cusid, $key, $APP_ID];
    }
    
    public function coupon($orderId) {
        
        
        $coupon_city = Db::connect(config('database.zong'))->table('coupon_city')->join('city', 'city.city_id=coupon_city.city_id', 'left')->field('GROUP_CONCAT(city.city) as cityName,GROUP_CONCAT(city.city_id) as cityIds,coupon_id')->group('coupon_id')->buildSql();
        
        $coupon_category = Db::connect(config('database.zong'))->table('coupon_category')->join('scheme_label_top', 'scheme_label_top.id=coupon_category.category_id', 'left')->field('GROUP_CONCAT(scheme_label_top.pid) as pid,coupon_id')->group('coupon_id')->buildSql();
        $c_time          = time();
        $list            = db('coupon_user', config('database.zong'))->join('order', 'order.telephone=coupon_user.mobile', 'left')->join('coupon', 'coupon.id=coupon_user.coupon_id', 'left')->join([$coupon_category => 'coupon_category'], 'coupon.id=coupon_category.coupon_id', 'left')->join([$coupon_city => 'coupon_city'], 'coupon.id=coupon_city.coupon_id', 'left')->where('coupon_user.usage_status', 1)->where('coupon.coupon_type', '<>', 3)
//            ->where('coupon_user.id', 239)
            ->where(function ($quer) use ($c_time) {
                $quer->where(['coupon.coupon_expire_type' => 1, 'coupon.coupon_expire_time_end' => ['>=', $c_time]])->whereOr(function ($quert) use ($c_time) {
                    $quert->where('coupon.coupon_expire_type', 2)->where('coupon_user.create_time + (coupon.coupon_expire_days * 86400) >= ' . $c_time);
                    
                });;
            })->where('order.order_id', $orderId)->field('coupon_user.id,coupon.coupon_title,coupon.coupon_limit,coupon.coupon_use_type,coupon.coupon_type,coupon.coupon_amount,coupon.coupon_discount,coupon.coupon_prize_quantity,coupon.coupon_prize_title,coupon.coupon_prize_unit,IF (coupon.coupon_expire_type = 1, coupon.coupon_expire_time_end, coupon_user.create_time + (coupon.coupon_expire_days * 86400)) as coupon_user_expire_e_time,order.pro_id,order.city_id as cityId,coupon_city.cityName,coupon_city.cityIds,coupon_category.pid')->group('coupon_user.id')->select();
        foreach ($list as $k => $item) {
            $list[$k]['coupon_user_expire_e_time'] = date('Y-m-d H:i', $item['coupon_user_expire_e_time']);
            $list[$k]['coupon_limit']              = $item['coupon_limit'] / 100;
            $list[$k]['coupon_amount']             = $item['coupon_amount'] / 100;
            $list[$k]['state']                     = 1;
            
            if ((!empty($item['pid']))) {
                
                foreach (explode(',', $item['pid']) as $o) {
                    
                    if ($item['pro_id'] == $o) {
                        $list[$k]['state'] = 1;
                        break;
                    } else {
                        $list[$k]['state'] = 2;
                    }
                    
                }
            }
            if ((!empty($item['cityIds'])) && $list[$k]['state'] == 1) {
                foreach (explode(',', $item['cityIds']) as $s) {
                    
                    if ($item['cityId'] == $s) {
                        $list[$k]['state'] = 1;
                        break;
                    } else {
                        $list[$k]['state'] = 2;
                    }
                    
                }
            }
        }
        return $list;
        
    }
    
    /*
    * 完工推送
    */
    public function PushCompletion($type, $order_id, $time = 1) {
        
        $order_payment_nodes = Db::connect(config('database.zong'))->table('order_payment_nodes')->join('order_setting', 'order_setting.order_id=order_payment_nodes.order_id', 'left')->where('order_payment_nodes.order_id', $order_id)->where('order_payment_nodes.node_code', $type)->field('order_payment_nodes.*,order_setting.payment_type')->find();
        if (!empty($order_payment_nodes) && $order_payment_nodes['payment_type'] != 2) {
            $ccPush1 = new ccPush($time, 'delay_template_pay_notice', 'delay_topic', 'delay.template_pay_notice');
            $Common  = self::order_for_payment($order_id);
            //签约金额
            $offer = (new OrderModel())->newOffer($order_id);
            $list  = ['order_id' => $order_id, 'pay_money' => $order_payment_nodes['node_money'], "all_money" => $offer['amount'], "paid" => $Common[0] + $Common[1], "id" => $order_payment_nodes['id'], "payment_id" => $order_payment_nodes['payment_id'], "remake" => $order_payment_nodes['node_title'],];
            if ($type == 2) {
                db('order_times')->where('order_id', $order_id)->where('interim_payment_time', 0)->update(['interim_payment_time' => time()]);
            }
            $ccPush1->push(json_encode($list), 'delay_template_pay_notice', 'delay_topic', 'delay.template_pay_notice');
            if ($order_payment_nodes['node_status'] == 1) {
                Db::connect(config('database.zong'))->table('order_payment_nodes')->where('order_id', $order_id)->where('node_code', $type)->update(['node_status' => 2, 'trigger_time' => time()]);
                Db::connect(config('database.zong'))->table('order_payment_nodes')->where('order_id', $order_id)->where('node_code', '<', $type)->where('node_status', 1)->update(['node_status' => 2, 'trigger_time' => time()]);
            }
            
        }
    }
    
    /*
     * 施工节点
     */
    public function ConstructionNode(string $capital, string $orderId) {
        //所有需要审核的节点
        $auxiliary_interactive = db('auxiliary_delivery_schedule')->Join('auxiliary_project_list', 'auxiliary_delivery_schedule.auxiliary_project_list_id=auxiliary_project_list.id', 'left')->whereIn('auxiliary_project_list.capital_id', $capital)->where('auxiliary_project_list.order_id', $orderId)->whereNull('auxiliary_project_list.delete_time')->whereNull('auxiliary_delivery_schedule.delete_time')->count();
        
        //已经审核的施工节点
        $auxiliary_interactiveCount = db('auxiliary_delivery_node')->Join('auxiliary_delivery_schedule', 'auxiliary_delivery_schedule.id=auxiliary_delivery_node.auxiliary_delivery_schedul_id', 'left')->Join('auxiliary_project_list', 'auxiliary_delivery_schedule.auxiliary_project_list_id=auxiliary_project_list.id', 'left')->whereIn('auxiliary_project_list.capital_id', $capital)->where('auxiliary_project_list.order_id', $orderId)->whereNull('auxiliary_project_list.delete_time')->whereNull('auxiliary_delivery_schedule.delete_time')->field('auxiliary_delivery_node.auxiliary_delivery_schedul_id,auxiliary_delivery_node.state')->group('auxiliary_delivery_node.auxiliary_delivery_schedul_id')->select();
        $reviewed                   = 0;
        foreach ($auxiliary_interactiveCount as $item) {
            if ($item['state'] == 1) {
                $reviewed += 1;
            }
        }
        
        return ['auxiliary_interactive' => $auxiliary_interactive, 'inTotal' => count($auxiliary_interactiveCount), 'reviewed' => $reviewed];
        
    }
    
    public static function approvalFieldExplain($types, $typeOfTransfinite = 0) {
        $type  = 0;
        $title = '';
        if ($types == 1) {
            $title = "清单总人工费增减金额";
            $type  = 6;
        } elseif ($types == 2) {
            $title = "清单总人工费增减金额";
            $type  = 9;
        } elseif ($types == 3) {
            if ($typeOfTransfinite == 1) {
                $title = "主合同增减优惠金额";
                $type  = 2;
            } elseif ($typeOfTransfinite == 2) {
                $title = "代购合同增减优惠金额";
                $type  = 3;
            }
        }
        
        return ['title' => $title, 'type' => $type];
    }
    
    /*
     * 获取推课宝盒上级
     */
    public function getGrouping($type, $cityId) {
        if ($type == 1) {
            switch ($cityId) {
                case 241:
                    $n = 2410000000620;
                    break;
                case 239:
                    $n = 2390000000545;
                    break;
                case 375:
                    $n = 3750000000003;
                    break;
                case 501:
                    $n = 5010000000003;
                    break;
                case 262:
                    $n = 2620000000014;
                    break;
                case 202:
                    $n = 2020000000002;
                    break;
                case 200:
                    $n = 2000000000001;
                    break;
                case 205:
                    $n = 2050000000116;
                    break;
                case 216:
                    $n = 2160000000100;
                    break;
                default:
                    $n = 0;
            }
        } else {
            switch ($cityId) {
                case 241:
                    $n = 2410000000523;
                    break;
                case 239:
                    $n = 2390000000498;
                    break;
                case 375:
                    $n = 3750000000004;
                    break;
                case 501:
                    $n = 5010000000003;
                    break;
                case 262:
                    $n = 2620000000008;
                    break;
                case 202:
                    $n = 2020000000003;
                    break;
                case 200:
                    $n = 2000000000002;
                    break;
                case 205:
                    $n = 2050000000117;
                    break;
                case 216:
                    $n = 2160000000100;
                    break;
                default:
                    $n = 0;
            }
        }
        return $n;
    }
    
    public static function city($orderid) {
        $shopowner = null;
        if (substr($orderid, 0, 3) == 241 || $orderid == 241) {
            $shopowner['city']    = 'cd';
            $shopowner['db']      = 'cd';
            $shopowner['city_id'] = 241;
        } elseif (substr($orderid, 0, 3) == 239 || $orderid == 239) {
            $shopowner['city']    = 'cq';
            $shopowner['db']      = 'cq';
            $shopowner['city_id'] = 239;
        } elseif (substr($orderid, 0, 3) == 172 || $orderid == 172) {
            $shopowner['city']    = 'wh';
            $shopowner['db']      = 'wh';
            $shopowner['city_id'] = 172;
        } elseif (substr($orderid, 0, 3) == 262 || $orderid == 262) {
            $shopowner['city']    = 'gy';
            $shopowner['db']      = 'gy';
            $shopowner['city_id'] = 262;
        } elseif (substr($orderid, 0, 3) == 375 || $orderid == 375) {
            $shopowner['city']    = 'sh';
            $shopowner['db']      = 'sh';
            $shopowner['city_id'] = 375;
        } elseif (substr($orderid, 0, 3) == 202 || $orderid == 202) {
            $shopowner['city']    = 'sz';
            $shopowner['db']      = 'sz';
            $shopowner['city_id'] = 202;
        } elseif (substr($orderid, 0, 3) == 501 || $orderid == 501) {
            $shopowner['city']    = 'bj';
            $shopowner['db']      = 'bj';
            $shopowner['city_id'] = 501;
        } elseif (substr($orderid, 0, 3) == 200 || $orderid == 200) {
            $shopowner['city']    = 'gz';
            $shopowner['db']      = 'gz';
            $shopowner['city_id'] = 200;
        } elseif (substr($orderid, 0, 3) == 205 || $orderid == 205) {
            $shopowner['city']    = 'fs';
            $shopowner['db']      = 'fs';
            $shopowner['city_id'] = 205;
        } elseif (substr($orderid, 0, 3) == 216 || $orderid == 216) {
            $shopowner['city']    = 'dg';
            $shopowner['db']      = 'dg';
            $shopowner['city_id'] = 216;
            
        }elseif (substr($orderid, 0, 3) == 246 || $orderid == 246) {
            $shopowner['city']    = 'my';
            $shopowner['db']      = 'my';
            $shopowner['city_id'] = 246;
            
        }
        return $shopowner;
    }
    
    /*
     * 甘特图公共接口
     */
    public function gantt($list, $type, $orderId, $envelopes_id,$systemTag,$time=0) {
        $result   = [];
        $tageList = [];
        foreach ($list as $k => $v) {
            $result[$v['groupingTitle']][] = $v;
        }
        if($time==0){
            $time=time();
        }   
        foreach ($result as $k => $list) {
            $schemeTag['title'] = $k;
            $daySum             = array_sum(array_column($result[$k], 'std_construction_volume'));
            $dry_period_days    = $result[$k][0]['dry_period_days'];
            $numberStr          = strval($daySum);
            $decimalPos         = strpos($numberStr, '.');
            $decimalPart        = 0;
            if ($decimalPos !== false) {
                $decimalPart = '0' . substr($numberStr, $decimalPos);
            }
            if ($decimalPart > 0.5 && $decimalPart > 0) {
                $daySum = $daySum + (1 - $decimalPart);
            } elseif ($decimalPart < 0.5 && $decimalPart > 0) {
                $daySum = $daySum + (0.5 - $decimalPart);
            }
            $schemeTag['daySum']        = $daySum;
            $schemeTag['dryPeriodDays'] = $dry_period_days;
            $schemeTag['data']          = $result[$k];
            $schemeTag['sort']          = $result[$k][0]['sort'];
            $schemeTag['day']           = $result[$k][0]['value'];
            
            $tageList[] = $schemeTag;
        } 
        if ($type == 1) {
            foreach ($tageList as $k => $list) {
                if ($list['daySum'] == 0) {
                    $list['daySum'] = 1;
                }
                
                if ($k == 0) {
                    if($time==0){
                        $startWorkCalendar = strtotime(date('Y-m-d 00:00:00', $time)) + 3 * 24 * 3600;
                    }else{
                        $startWorkCalendar = strtotime(date('Y-m-d 00:00:00', $time)) ;
                    }
                    
                    $actual            = $startWorkCalendar;
                    $value             = 0;
                } else {
                    $actual            = $tageList[$k - 1]['actual'];
                    $work_calendarIss  = db('work_calendar', config('database.zong'))->where('data_string', date('Y-m-d', $actual))->find();
                    $value             = $list['data'][0]['value'];
                    $startWorkCalendar = strtotime($tageList[$k - 1]['startWorkCalendar']) + $value * 24 * 3600;
                    $actual            = $actual + $value * 24 * 3600;
                    if ($work_calendarIss['type'] == 1) {
                        $actual = $startWorkCalendar;
                    }
                    
                    if ($list['sort'] > $tageList[$k - 1]['sort'] && $value == 0) {
                        if ($tageList[$k - 1]['timeList'][count($tageList[$k - 1]['timeList']) - 1]['halfADay'] == '-0.5') {
                            $startWorkCalendar = $tageList[$k - 1]['workCalendars'];
                            $actual            = $startWorkCalendar;
                        } elseif ($tageList[$k - 1]['timeList'][count($tageList[$k - 1]['timeList']) - 1]['halfADay'] == 1) {
                            $startWorkCalendar = strtotime($tageList[$k - 1]['timeList'][count($tageList[$k - 1]['timeList']) - 1]['data_string']) + 1 * 24 * 3600;
                            $actual            = $startWorkCalendar;
                        } elseif ($tageList[$k - 1]['timeList'][count($tageList[$k - 1]['timeList']) - 1]['halfADay'] == 0.5) {
                            $startWorkCalendar = strtotime($tageList[$k - 1]['timeList'][count($tageList[$k - 1]['timeList']) - 1]['data_string']) + 1 * 24 * 3600;
                            $actual            = $startWorkCalendar;
                        }
                        
                    }
                    if ($list['data'][0]['agency'] == 1) {
                        $actual            = $tageList[0]['startWorkCalendars'] ;
                        $startWorkCalendar = $actual;
                        
                    }
                }
                $tageList[$k]['actual'] = $startWorkCalendar;
                $j                      = 0;
                if ($k != 0) {
                    if ($list['sort'] == $tageList[$k - 1]['sort']) {
                        $actual            = $tageList[$k - 1]['actual'];
                        $startWorkCalendar = strtotime($tageList[$k - 1]['startWorkCalendar']);
                    }
                }
                $work_calendarIs = db('work_calendar', config('database.zong'))->where('data_string', date('Y-m-d', $actual))->find();
                if ($work_calendarIs['is_work'] != 1) {
                    for ($x = 0; $x <= 99; $x++) {
                        $work_calendarIsGong = db('work_calendar', config('database.zong'))->where('data_string', date('Y-m-d', $actual + ($x * 24 * 3600)))->find();
                        if ($work_calendarIsGong['is_work'] == 1) {
                            $actual = strtotime($work_calendarIsGong['data_string']);
                            break;
                        }
                    }
                }
                //取整算天数
                $rounding = ceil($list['daySum']);
                if (date('H', $actual) == '12' && $list['daySum'] >= 1) {
                    $rounding = $rounding + 1;
                    if ($k != 0) {
                        if ($list['sort'] == $tageList[$k - 1]['sort']) {
                            $rounding = $rounding - 1;
                        }
                    }
                    
                }
                
                $numberStr   = strval($list['daySum']);
                $decimalPos  = strpos($numberStr, '.');
                $decimalPart = 0;
                if ($decimalPos !== false) {
                    $decimalPart = '0' . substr($numberStr, $decimalPos);
                }
                $work_calendar = db('work_calendar', config('database.zong'))->where('data_string', '>=', date('Y-m-d', $actual))->where('is_work', 1)->order('data_string ACS')->limit($rounding)->field('year,month,day,week,is_work,type,data_string')->select();
                
                $tageList[$k]['startWorkCalendar'] = date('Y-m-d H:i:s', $startWorkCalendar);
//                if ($tageList[$k]['actual'] > strtotime($tageList[$k]['startWorkCalendar'])) {
//                    $work_calendarsList = db('work_calendar', config('database.zong'))->where('data_string', '>=', date('Y-m-d', strtotime($tageList[$k]['startWorkCalendar'])))->find();
//                    if ($work_calendarsList['is_work'] == 1) {
//                        $tageList[$k]['startWorkCalendars'] = $tageList[$k]['actual'];
//                        $tageList[$k]['startWorkCalendar']  = date('Y-m-d H:i:s', $tageList[$k]['actual']);
//
//                    }
//                }
                
                $tageList[$k]['day']           = 0;
                $tageList[$k]['id']            = $list['data'][0]['id'];
                $tageList[$k]['categoryName']  = $list['data'][0]['categoryName'];
                $tageList[$k]['restDay']       = 0;
                $tageList[$k]['actual']        = $actual;
                $tageList[$k]['completionTag'] = 0;
                if ($list['data'][0]['agency'] == 1) {
                    $tageList[$k]['completionTag'] = 1;
                    
                }
                $tageList[$k]['startWorkCalendars'] = $startWorkCalendar;
                if (date('H', $tageList[$k]['actual']) != '00') {
                    $decimalPart = $decimalPart + 0.5;
                }
                $tageList[$k]['workCalendars'] = strtotime($work_calendar[count($work_calendar) - 1]['data_string']) + $decimalPart * 24 * 3600;
                $tageList[$k]['workCalendar']  = date('Y-m-d H:i:s', $tageList[$k]['workCalendars']);
                $dry_period_days               = 0;
                if ($list['dryPeriodDays'] != '0.00') {
                    $dry_period_days               = ceil($list['dryPeriodDays']);
                    $tageList[$k]['workCalendars'] = strtotime($work_calendar[count($work_calendar) - 1]['data_string']) + $decimalPart * 24 * 3600 + $dry_period_days * 24 * 3600;
                    $tageList[$k]['workCalendar']  = date('Y-m-d H:i:s', $tageList[$k]['workCalendars']);
                }
                $work_calendarList = db('work_calendar', config('database.zong'))->whereBetween('data_string', [date('Y-m-d', strtotime($tageList[$k]['startWorkCalendar'])), date('Y-m-d', strtotime($work_calendar[count($work_calendar) - 1]['data_string']))])->order('data_string ACS')->field('year,month,day,week,is_work,type,data_string')->select();
                $zhi               = array_sum(array_column($list['data'], 'std_construction_volume'));
                foreach ($work_calendarList as $m => $u) {
                    $work_calendarList[$m]['agency']        = $list['data'][0]['agency'];
                    $work_calendarList[$m]['desiccation']   = 0;//是不是干燥器等于0 不是干燥器  等于1是干燥器
                    $work_calendarList[$m]['completionTag'] = 0;
                    $work_calendarList[$m]['halfADay']      = 1;
                    if (date('H', $tageList[$k]['startWorkCalendars']) != '00' && $u['is_work'] == 1) {
                        $work_calendarList[0]['halfADay'] = '0.5';
                    }
                    if (date('H', $tageList[$k]['workCalendars']) != '00' && $u['is_work'] == 1) {
                        $work_calendarList[count($work_calendarList) - 1]['halfADay'] = '-0.5';
                    }
                    
                }
                if ($work_calendarList[count($work_calendarList) - 1]['halfADay'] == '-0.5' && $dry_period_days != 0) {
                    $work_calendarListDate = db('work_calendar', config('database.zong'))->where('data_string', '>=', $work_calendarList[count($work_calendarList) - 1]['data_string'])->limit($dry_period_days + 1)->order('data_string ACS')->field('year,month,day,week,is_work,type,data_string')->select();
                    foreach ($work_calendarListDate as $J => $n) {
                        $work_calendarListDate[$J]['agency']        = $list['data'][0]['agency'];
                        $work_calendarListDate[$J]['desiccation']   = 1;
                        $work_calendarListDate[$J]['halfADay']      = 1;
                        $work_calendarListDate[$J]['completionTag'] = 0;
                        if ($J == 0) {
                            $work_calendarListDate[0]['halfADay'] = 0.5;
                        }
                        if ($J == count($work_calendarListDate) - 1) {
                            $work_calendarListDate[count($work_calendarListDate) - 1]['halfADay'] = '-0.5';
                        }
                        
                    }
                    $work_calendarList = array_merge($work_calendarList, $work_calendarListDate);
                }
                if ($work_calendarList[count($work_calendarList) - 1]['halfADay'] != '-0.5' && $dry_period_days != 0) {
                    $work_calendarListDate = db('work_calendar', config('database.zong'))->where('data_string', '>', $work_calendarList[count($work_calendarList) - 1]['data_string'])->limit($dry_period_days)->order('data_string ACS')->field('year,month,day,week,is_work,type,data_string')->select();
                    foreach ($work_calendarListDate as $J => $n) {
                        $work_calendarListDate[$J]['agency']        = $list['data'][0]['agency'];
                        $work_calendarListDate[$J]['desiccation']   = 1;
                        $work_calendarListDate[$J]['halfADay']      = 1;
                        $work_calendarListDate[$J]['completionTag'] = 0;
                        
                        
                    }
                    $work_calendarList = array_merge($work_calendarList, $work_calendarListDate);
                }
                $tageList[$k]['timeList'] = $work_calendarList;
                $work_calendarLists       = $work_calendarList;
                foreach ($work_calendarLists as $o => $m) {
                    if ($m['halfADay'] == 1) {
                        $work_calendarLists[$o]['data_string'] = date('Y-m-d', strtotime($m['data_string']) + 1 * 24 * 3600);
                    }
                }
                $max                 = array_column($work_calendarLists, 'data_string');
                $max                 = max($max);
                $tageList[$k]['max'] = $max;
                
            }
            
        } else {
            
            foreach ($tageList as $k => $list) {
                $j = 0;
                if ($list['daySum'] == 0) {
                    $list['daySum'] = 1;
                }
                $daySum = $list['daySum'];
                if ($k == 0) {
                    if($time==0){
                        $startWorkCalendar = strtotime(date('Y-m-d 00:00:00', $time)) + 3 * 24 * 3600;
                    }else{
                        $startWorkCalendar = strtotime(date('Y-m-d 00:00:00', $time)) ;
                    }
                    
                    $actual            = $startWorkCalendar;
                } else {
                    $actual          = $tageList[$k - 1]['workCalendars'];
                    $daySums         = $list['daySum'];
                    $work_calendarIs = db('work_calendar', config('database.zong'))->where('data_string', date('Y-m-d', $actual))->find();
                    if (date('H', $actual) == '12' && $work_calendarIs['is_work'] == 1) {
                        $list['daySum'] = $list['daySum'] + 0.5;
                    }
                    $numberStr1  = strval($tageList[$k - 1]['daySum']);
                    $decimalPos1 = strpos($numberStr1, '.');
                    if ($decimalPos1 == false && date('H', $tageList[$k - 1]['actual']) == 00) {
                        $actual = $actual + 1 * 24 * 3600;
                    }
                    if ($list['data'][0]['agency'] == 1) {
                        $actual         = $tageList[0]['startWorkCalendars'] ;
                        $list['daySum'] = $daySums;
                    }
                    $startWorkCalendar = $actual;
                }
                
                //取整算天数
                $rounding = ceil($list['daySum']);
                
                $work_calendarIs = db('work_calendar', config('database.zong'))->where('data_string', date('Y-m-d', $actual))->find();
                if ($work_calendarIs['is_work'] != 1) {
                    for ($x = 0; $x <= 99; $x++) {
                        $work_calendarIsGong = db('work_calendar', config('database.zong'))->where('data_string', date('Y-m-d', $actual + ($x * 24 * 3600)))->find();
                        if ($work_calendarIsGong['is_work'] == 1) {
                            $actual = strtotime($work_calendarIsGong['data_string']);
                            break;
                        }
                    }
                }
                $numberStr   = strval($daySum);
                $decimalPos  = strpos($numberStr, '.');
                $decimalPart = 0;
                if ($decimalPos !== false) {
                    $decimalPart = '0' . substr($numberStr, $decimalPos);
                }
                
                $work_calendar                 = db('work_calendar', config('database.zong'))->where('data_string', '>=', date('Y-m-d', $actual))->where('is_work', 1)->order('data_string ACS')->limit($rounding)->field('year,month,day,week,is_work,type,data_string')->select();
                $tageList[$k]['completionTag'] = 0;
                if ($list['data'][0]['agency'] == 1) {
                    $tageList[$k]['completionTag'] = 1;
                    
                }
                $tageList[$k]['startWorkCalendar']  = date('Y-m-d H:i:s', $startWorkCalendar);
                $tageList[$k]['day']                = 0;
                $tageList[$k]['restDay']            = 0;
                $tageList[$k]['id']                 = $list['data'][0]['id'];
                $tageList[$k]['categoryName']       = $list['data'][0]['categoryName'];
                $tageList[$k]['actual']             = $actual;
                $tageList[$k]['startWorkCalendars'] = strtotime(date('Y-m-d H:i:s', $startWorkCalendar));
                if (date('H', $tageList[$k]['actual']) == '12') {
                    
                    $decimalPart = $decimalPart + 0.5;
                }
                $tageList[$k]['workCalendars'] = strtotime($work_calendar[count($work_calendar) - 1]['data_string']) + $decimalPart * 24 * 3600;
                $tageList[$k]['workCalendar']  = date('Y-m-d H:i:s', $tageList[$k]['workCalendars']);
                $dry_period_days               = 0;
                
                if ($list['dryPeriodDays'] != '0.00') {
                    
                    $dry_period_days               = ceil($list['dryPeriodDays']);
                    $tageList[$k]['workCalendars'] = $tageList[$k]['workCalendars'] + $dry_period_days * 24 * 3600;
                    $tageList[$k]['workCalendar']  = date('Y-m-d H:i:s', $tageList[$k]['workCalendars']);
                }
                
                $work_calendarList = db('work_calendar', config('database.zong'))->whereBetween('data_string', [date('Y-m-d', strtotime($tageList[$k]['startWorkCalendar'])), date('Y-m-d', strtotime($work_calendar[count($work_calendar) - 1]['data_string']))])->order('data_string ACS')->field('year,month,day,week,is_work,type,data_string')->select();
                $zhi               = array_sum(array_column($list['data'], 'std_construction_volume'));
                foreach ($work_calendarList as $m => $u) {
                    $work_calendarList[$m]['agency']          = $list['data'][0]['agency'];
                    $work_calendarList[$m]['halfADay']        = 1;
                    $work_calendarList[$m]['completionTag']   = 0;
                    $work_calendarListDate[$m]['desiccation'] = 0;
                    if (date('H', $tageList[$k]['startWorkCalendars']) != '00' && $u['is_work'] == 1) {
                        $work_calendarList[0]['halfADay'] = '0.5';
                    }
                    if (date('H', $tageList[$k]['workCalendars']) != '00' && $u['is_work'] == 1) {
                        $work_calendarList[count($work_calendarList) - 1]['halfADay'] = '-0.5';
                    }
                    
                    
                }
                
                if ($work_calendarList[count($work_calendarList) - 1]['halfADay'] == '-0.5' && $dry_period_days != 0) {
                    $work_calendarListDate = db('work_calendar', config('database.zong'))->where('data_string', '>=', $work_calendarList[count($work_calendarList) - 1]['data_string'])->limit($dry_period_days + 1)->order('data_string ACS')->field('year,month,day,week,is_work,type,data_string')->select();
                    foreach ($work_calendarListDate as $J => $n) {
                        $work_calendarListDate[$J]['agency']        = $list['data'][0]['agency'];
                        $work_calendarListDate[$J]['desiccation']   = 1;
                        $work_calendarListDate[$J]['halfADay']      = 1;
                        $work_calendarListDate[$J]['completionTag'] = 0;
                        if ($J == 0) {
                            $work_calendarListDate[0]['halfADay'] = 0.5;
                        }
                        if ($J == count($work_calendarListDate) - 1) {
                            $work_calendarListDate[count($work_calendarListDate) - 1]['halfADay'] = '-0.5';
                        }
                        
                    }
                    $work_calendarList = array_merge($work_calendarList, $work_calendarListDate);
                }
                if ($work_calendarList[count($work_calendarList) - 1]['halfADay'] != '-0.5' && $dry_period_days != 0) {
                    $work_calendarListDate = db('work_calendar', config('database.zong'))->where('data_string', '>', $work_calendarList[count($work_calendarList) - 1]['data_string'])->limit($dry_period_days)->order('data_string ACS')->field('year,month,day,week,is_work,type,data_string')->select();
                    foreach ($work_calendarListDate as $J => $n) {
                        $work_calendarListDate[$J]['agency']        = $list['data'][0]['agency'];
                        $work_calendarListDate[$J]['desiccation']   = 1;
                        $work_calendarListDate[$J]['completionTag'] = 0;
                        $work_calendarListDate[$J]['halfADay']      = 1;
                        
                        
                    }
                    $work_calendarList = array_merge($work_calendarList, $work_calendarListDate);
                }
                
                $tageList[$k]['timeList'] = $work_calendarList;
                $work_calendarLists       = $work_calendarList;
                foreach ($work_calendarLists as $o => $m) {
                    if ($m['halfADay'] == 1) {
                        $work_calendarLists[$o]['data_string'] = date('Y-m-d', strtotime($m['data_string']) + 1 * 24 * 3600);
                    }
                }
                $max                 = array_column($work_calendarLists, 'data_string');
                $max                 = max($max);
                $tageList[$k]['max'] = $max;
                
            }
        }
        $ganttDay      = 0;
        $work_calendar = [];
        $weekday       = [];
    
        if (!empty($tageList)) {
            $tageList = $this->increaseProjectDuration($envelopes_id, $type, $orderId, $systemTag, $tageList);
        }
        return ['list' => empty($tageList) ? null : $tageList['list'], 'date' => empty($tageList) ? null : $tageList['date'], 'ganttDay' => empty($tageList) ? 0 : $tageList['ganttDay'], 'weekday' => empty($tageList['weekday']) ? 1 : $tageList['weekday']];
        
        
    }
    
    /*
     * 增加完工验收工期
     */
    public function increaseProjectDuration($envelopes_id, $type, $orderId, $systemTag, $tageList) {
        
        $mo      = 0;
        $wangong = 0;
        if ($envelopes_id != 0) {
            $order_defer = Db::connect(config('database.zong'))->table('order_defer')->where('order_id', $orderId)->where('deleted_at', 0)->where('status', 2)->sum('days');
            $gong        = db('envelopes')->where('envelopes_id', $envelopes_id)->value('gong');
            $mix         = min(array_column($tageList, 'startWorkCalendar'));
            $max         = max(array_column($tageList, 'workCalendar'));
            $weekday     = db('work_calendar', config('database.zong'))->where('data_string', '>=', date('Y-m-d', strtotime($mix)))->where('data_string', '<=', date('Y-m-d', strtotime($max)))->where('is_work', 1)->order('data_string ACS')->field('year,week,is_work,type,data_string')->select();
//                $approval_record = db('approval_record', config('database.zong'))->where('relation_id', $envelopes_id)->where('order_id', $orderId)->where('type', 10)->where('status', 0)->value('change_value');
//                if (!empty($approval_record)) {
//                    $gong = $gong + $approval_record;
//                }

            if ((!empty($order_defer) || $gong > count($weekday) + 1) && $systemTag == 0) {
                $mo          = 1;
                $quitDates   = array_column($tageList, 'max');
                $maxItemKey  = array_search(max($quitDates), $quitDates);
                $tageLists[] = array_merge($tageList[$maxItemKey]);
                $daySum4     = 0;
                if ($gong > (count($weekday) + 1)) {
                    $daySum4 = $gong - (count($weekday) + 1);
                }
                $daySum4  = $daySum4 + $order_defer;
                $chao     = $this->SplicingGanttCharts($tageLists, $envelopes_id, '延期工序', $orderId, $daySum4, 1, $type);
                $tageList = array_merge($tageList, $chao);
            }
            
        }
        
        if ($mo == 0) {
            $quitDates   = array_column($tageList, 'max');
            $maxItemKey  = array_search(max($quitDates), $quitDates);
            $tageLists[] = array_merge($tageList[$maxItemKey]);
        } else {
            $tageLists = $tageList;
        }
        $chao1 = $this->SplicingGanttCharts($tageLists, $envelopes_id, '完工验收', $orderId, 1, 0, $type);
        
        if (!empty($chao1)) {
            if ($chao1[0]['timeList'][count($chao1[0]['timeList']) - 1]['is_work'] == 0) {
                $wangong = 1;
            }
            foreach ($chao1 as $k => $l) {
                foreach ($l['timeList'] as $o => $t) {
                    $chao1[$k]['timeList'][$o]['completionType'] = 1;
                }
            }
        }
        $tageList = array_merge($tageList, $chao1);
        
        $mix           = min(array_column($tageList, 'startWorkCalendar'));
        $max           = max(array_column($tageList, 'workCalendar'));
        $work_calendar = db('work_calendar', config('database.zong'))->where('data_string', '>=', date('Y-m-d', strtotime($mix)))->where('data_string', '<=', date('Y-m-d', strtotime($max)))->order('data_string ACS')->field('year,week,is_work,type,data_string')->select();
        $ganttDay      = count($work_calendar);
        $weekday       = db('work_calendar', config('database.zong'))->where('data_string', '>=', date('Y-m-d', strtotime($mix)))->where('data_string', '<=', date('Y-m-d', strtotime($max)))->where('is_work', 1)->order('data_string ACS')->field('year,week,is_work,type,data_string')->select();
        return ['list' => $tageList, 'date' => $work_calendar, 'ganttDay' => $ganttDay, 'weekday' => count($weekday) + $wangong];
        
    }
    
    /*
    拼接甘特图
    */
    public function SplicingGanttCharts($tageList, $envelopes_id, $title, $orderId, $daySum, $type, $types) {
        if ($tageList[count($tageList) - 1]['timeList'][count($tageList[count($tageList) - 1]['timeList']) - 1]['halfADay'] == '-0.5') {
            $daySum4            = $daySum + 1;
            $startWorkCalendars = $tageList[count($tageList) - 1]['workCalendars'];
            if ($type == 1) {
                
                $work_calendarListDates = db('work_calendar', config('database.zong'))->where('data_string', '>=', date('Y-m-d', $startWorkCalendars))->where('is_work', 1)->limit($daySum4)->order('data_string ACS')->field('year,month,day,week,is_work,type,data_string')->select();
                $work_calendarListDates = db('work_calendar', config('database.zong'))->whereBetween('data_string', [date('Y-m-d', $startWorkCalendars), $work_calendarListDates[count($work_calendarListDates) - 1]['data_string']])->order('data_string ACS')->field('year,month,day,week,is_work,type,data_string')->select();
                
            } else {
                $work_calendarListDates = db('work_calendar', config('database.zong'))->where('data_string', '>=', date('Y-m-d', $startWorkCalendars))->limit($daySum4)->order('data_string ACS')->field('year,month,day,week,is_work,type,data_string')->select();
                
            }
            
            foreach ($work_calendarListDates as $k => $o) {
                $work_calendarListDates[$k]['desiccation']   = 0;
                $work_calendarListDates[$k]['halfADay']      = 1;
                $work_calendarListDates[$k]['completionTag'] = 1;
                if ($k == 0) {
                    $work_calendarListDates[$k]['halfADay'] = 0.5;
                }
                if ($k == count($work_calendarListDates) - 1) {
                    $work_calendarListDates[$k]['halfADay'] = '-0.5';
                }
            }
            
        } else {
            $daySum4            = $daySum;
            $startWorkCalendars = $tageList[count($tageList) - 1]['workCalendars'];
            if ($type == 1) {
                $work_calendarListDates = db('work_calendar', config('database.zong'))->where('data_string', '>=', date('Y-m-d', $startWorkCalendars))->where('is_work', 1)->limit($daySum4)->order('data_string ACS')->field('year,month,day,week,is_work,type,data_string')->select();
                if ($tageList[count($tageList) - 1]['timeList'][count($tageList[count($tageList) - 1]['timeList']) - 1]['data_string'] == date('Y-m-d', $startWorkCalendars)) {
                    $startWorkCalendars     = $startWorkCalendars + 1 * 24 * 3600;
                    $work_calendarListDates = db('work_calendar', config('database.zong'))->where('data_string', '>=', date('Y-m-d', $startWorkCalendars))->where('is_work', 1)->limit($daySum4)->order('data_string ACS')->field('year,month,day,week,is_work,type,data_string')->select();
                }
                $work_calendarListDates = db('work_calendar', config('database.zong'))->whereBetween('data_string', [date('Y-m-d', $startWorkCalendars), $work_calendarListDates[count($work_calendarListDates) - 1]['data_string']])->order('data_string ACS')->field('year,month,day,week,is_work,type,data_string')->select();
            } else {
                $work_calendarListDates = db('work_calendar', config('database.zong'))->where('data_string', '>=', date('Y-m-d', $startWorkCalendars))->limit($daySum4)->order('data_string ACS')->field('year,month,day,week,is_work,type,data_string')->select();
                
                if ($tageList[count($tageList) - 1]['timeList'][count($tageList[count($tageList) - 1]['timeList']) - 1]['data_string'] == date('Y-m-d', $startWorkCalendars)) {
                    $startWorkCalendars     = $startWorkCalendars + 1 * 24 * 3600;
                    $work_calendarListDates = db('work_calendar', config('database.zong'))->where('data_string', '>=', date('Y-m-d', $startWorkCalendars))->limit($daySum4)->order('data_string ACS')->field('year,month,day,week,is_work,type,data_string')->select();
                }
            }
            foreach ($work_calendarListDates as $k => $o) {
                $work_calendarListDates[$k]['desiccation']   = 0;
                $work_calendarListDates[$k]['completionTag'] = 1;
                $work_calendarListDates[$k]['agency']        = 0;
                $work_calendarListDates[$k]['halfADay']      = 1;
            }
        }
        $workCalendars = strtotime($work_calendarListDates[count($work_calendarListDates) - 1]['data_string']);
        if ($work_calendarListDates[count($work_calendarListDates) - 1]['halfADay'] != 1) {
            $workCalendars = $workCalendars + abs($work_calendarListDates[count($work_calendarListDates) - 1]['halfADay']) * 24 * 3600;
        }
        $work_calendarLists = $work_calendarListDates;
        foreach ($work_calendarLists as $o => $m) {
            if ($m['halfADay'] == 1) {
                $work_calendarLists[$o]['data_string'] = date('Y-m-d', strtotime($m['data_string']) + 1 * 24 * 3600);
            }
        }
        $max  = array_column($work_calendarLists, 'data_string');
        $max  = max($max);
        $chao = [["title" => $title, "daySum" => $daySum, "day" => 0, "max" => $max, "restDay" => 0, "completionTag" => 1, 'data' => [["categoryName" => $title, "title" => $title, "fang" => 0, "sort" => 0, "groupingTitle" => 0, "std_construction_volume" => 0, "dry_period_days" => 0, "agency" => 0, "value" => 0, "id" => 0]], "startWorkCalendar" => date('Y-m-d H:i:s', $startWorkCalendars), "startWorkCalendars" => $startWorkCalendars, "workCalendar" => date('Y-m-d H:i:s', $workCalendars), "workCalendars" => $workCalendars, 'timeList' => $work_calendarListDates
        
        ]];
        return $chao;
    }
    
    /*
     * 是否设置开工计划
     */
    public function isStart($orderId,$userInfo) {
        $sta_time     = db('startup')->where('orders_id', $orderId)->value('sta_time');
        $signing_time = db('order_times')->where('order_id', $orderId)->value('signing_time');
        if ((empty($sta_time) || $sta_time == 0) && $signing_time > 1718294400 && $userInfo['confirm_work_time']==1) {
            r_date(null, 302, '未设置开工计划，无法操作');
        }
        return true;
    }
    
    /*
     * 开工日志
     */
    public function StartJournal($orderId, $userId, $username, $operator_role = 2, $event_desc = '店长开工', $event = 2) {
        \db('order_start_work_log', config('database.zong'))->insert(['order_id' => $orderId, 'event' => $event, 'event_desc' => $event_desc, 'operator_role' => $operator_role, 'operator_id' => $userId, 'operator_name' => $username, 'create_time' => time()]);
    }
    
    /*
  * 图片资源类型：1商机预约，2跟进记录，3上门打卡,4上门拍照，5Ai设计，6报价关联清单，7收款凭证，8施工交接，9工序节点，10工地打卡,11费用报销，12代购请款，13超限优惠，14完工验收
  */
    public function MultimediaResources($orderId, $userId, $url, $type) {
        $list = [];
        if (is_array($url)) {
            foreach ($url as $l) {
                // $headers = isset($l['path']) ? get_headers($l['path'], 1) : get_headers($l, 1);
                // if (isset($headers['Content-Length'])) {
                //     $fileSize = $headers['Content-Length'];
                //     $size     = $fileSize;
                // } else {
                //     $size = 0;
                // }
                // $mime_type = isset($l['path']) ? getimagesize($l['path'])['mime'] : getimagesize($l)['mime'];
                $md5       = isset($l['path']) ? md5_file($l['path']) : md5_file($l);
                $path      = isset($l['path']) ? parse_url($l['path'])['path'] : parse_url($l)['path'];
                
                $list[] = ['order_id' => $orderId, 'role_type' => 1, 'user_id' => $userId, 'type' => $type, 'mime_type' => 1, 'path' => $path, 'size' => 0, 'md5' => $md5, 'status' => 1, 'created_at' => time()];
            }
        } else {
            // $headers = get_headers($url, 1);
            // if (isset($headers['Content-Length'])) {
            //     $fileSize = $headers['Content-Length'];
            //     $size     = $fileSize;
            // } else {
            //     $size = 0;
            // }
            // $mime_type = getimagesize($url)['mime'];
            $md5       = md5_file($url);
            $path      = parse_url($url)['path'];
            
            $list[] = ['order_id' => $orderId, 'role_type' => 1, 'user_id' => $userId, 'type' => $type, 'mime_type' => 1, 'path' => $path, 'size' => 0, 'md5' => $md5, 'status' => 1, 'created_at' => time()];
        }
        \db('order_resource')->insertAll($list);
    }
    
    /*
     * 报销可用额度
     */
    public function availableReimbursementLimit($orderId, $capitalId) {
        
        $priceMoney = db('reimbursement_capital_beforehand')->where(function ($quer) {
            $quer->where('reimbursement.status', 0)->whereOr('reimbursement.status', 3);
        })->where('reimbursement_capital_beforehand.capital_id', $capitalId)->join('reimbursement', 'reimbursement.id=reimbursement_capital_beforehand.reimbursement_id', 'left')->sum('reimbursement_capital_beforehand.beforehand_money');
        return empty($priceMoney) ? 0 : $priceMoney;
        
    }
    
    /*
     * 分配报销可用额度
     */
    public function allocateAvailableReimbursementLimits($orderId, $capitalId, $labor_cost_reimbursement = 0, $projectId, $type, $allocationAmount, $uniqueNumber = 0) {
        $detaileds = db('detailed')->where('detailed_id', $projectId)->field('reimbursement,detailed_category_id')->find();
        $detailed  = explode(',', $detaileds['reimbursement']);
        if (!in_array('1', $detailed) && !in_array('2', $detailed)) {
            return false;
        }
        $detailedList = [1, 2];
        
        $capital = db('capital')->where(function ($quer) {
            $quer->where('capital.approve', 0)->whereOr('capital.approve', 1)->whereOr('capital.approve', 2);
        })->where('capital.types', 1)->where('capital.enable', 1)->join('detailed', 'detailed.detailed_id=capital.projectId', 'left')->join('app_user_order_capital', 'app_user_order_capital.capital_id=capital.capital_id and app_user_order_capital.deleted_at is null', 'left')->where('capital.ordesr_id', $orderId)->where(function ($query) use ($detailedList) {
            foreach ($detailedList as $value) {
                $query->whereOrRaw("FIND_IN_SET({$value}, detailed.reimbursement) > 0", [], 'string');
            }
        })->where('detailed.detailed_category_id', $detaileds['detailed_category_id'])->field([ '(capital.labor_cost+capital.labor_cost_material) as labor_cost', 'capital.to_price', 'capital.labor_cost_reimbursement', '(SELECT COALESCE(SUM(personal_price + cooperation_price), 0) FROM app_user_order_capital WHERE app_user_order_capital.capital_id = capital.capital_id AND app_user_order_capital.deleted_at IS NULL) as total_personal_cooperation_price', 'capital.capital_id', 'detailed.reimbursement'])->where('capital.capital_id', '<>', $capitalId)->group('capital.capital_id');
        if ($type == 3 && $uniqueNumber !=0) {
            $capital = $capital->where('capital.uniqueNumber', '<>', $uniqueNumber);
        }
        $capital = $capital->select();
        if (empty($capital) && $allocationAmount !=0) {
            return ['code' => 300, 'msg' => "因该清单工费额度已被发放或报销，无法减项，若仍然要减项，请企业微信提交特殊审批，通过后联系张斌"];
        }
        $list = [];
        foreach ($capital as $k => $item) {
            $priceMoney                                      = db('reimbursement_capital_beforehand')->where('reimbursement.status', 0)->where('reimbursement_capital_beforehand.capital_id', $item['capital_id'])->join('reimbursement', 'reimbursement.id=reimbursement_capital_beforehand.reimbursement_id', 'left')->sum('reimbursement_capital_beforehand.beforehand_money');
            $capital_minus_beforehand                        = db('capital_minus_beforehand')->where('capital_minus_beforehand.delete_time', 0)->where('capital_minus_beforehand.capital_id', $item['capital_id'])->sum('capital_minus_beforehand.beforehand_money');
            $capital[$k]['reimbursement_capital_beforehand'] = $priceMoney;
            $capital[$k]['totalPriceSum']                    = (string)($item['labor_cost'] - $item['labor_cost_reimbursement'] - $item['total_personal_cooperation_price'] - $priceMoney - $capital_minus_beforehand);
        }
        
        $chao = [];
        foreach ($capital as $k => $item) {
            $op                   = (string)(array_sum(array_column($capital, 'totalPriceSum')));
            $capital[$k]['keSum'] = $op;
            $capital[$k]['bi']    = empty($capital[$k]['keSum']) ? 0 : (string)$item['totalPriceSum'] / $capital[$k]['keSum'];
            if ($k == count($capital) - 1) {
                $capital[$k]['fen'] = (string)($allocationAmount - array_sum(array_column($capital, 'fen')));
                if ($capital[$k]['fen'] > $item['totalPriceSum']) {
                    $capital[$k]['fen'] = $item['totalPriceSum'];
                }
            } else {
                $capital[$k]['fen'] = (string)round($allocationAmount * $capital[$k]['bi'], 2);
                if ($capital[$k]['fen'] > $item['totalPriceSum']) {
                    $capital[$k]['fen'] = $item['totalPriceSum'];
                }
            }
            
            
        }
        $listArray        = [];
        $tageList         = [];
        $tageList['chao'] = (string)($allocationAmount - array_sum(array_column($capital, 'fen')));
        $to_price=0;
        if(!empty($capital)){
            $to_price         = max(array_column($capital, 'to_price'));
        }
       
        foreach ($capital as $k => $g) {
            array_push($listArray, ['beforehand_money' => $g['fen'], 'capital_id' => $g['capital_id'], 'minus_id' => $capitalId, 'types' => $type, 'create_time' => time()]);
            if ($g['to_price'] == $to_price) {
                $tageList['List'][] = $g;
            }
            
        }
        return (['code' => 200, 'chao' => $tageList, 'beforehand' => $listArray]);
        
    }
    
    /*
     * 删除从新算额度
     */
    public function deleteRecalculatedCreditLimit($orderId, $capital_id = 0, $type = 0, $types = 0, $uniqueNumber=0) {
        $capitalMinusBeforehand = db('capital_minus_beforehand')->join('capital', 'capital.capital_id=capital_minus_beforehand.minus_id', 'left')->join('detailed', 'detailed.detailed_id=capital.projectId', 'left')->field('capital.projectId,capital.ordesr_id,(capital.labor_cost+capital.labor_cost_material) as labor_cost,capital.capital_id,capital.labor_cost_reimbursement,detailed.detailed_category_id,capital_minus_beforehand.minus_id,capital_minus_beforehand.types,capital.uniqueNumber')->group('capital_minus_beforehand.minus_id')->where('capital.ordesr_id',$orderId)->where('capital_minus_beforehand.delete_time', 0)->order('id asc')->select();
        if (empty($capitalMinusBeforehand)) {
            return true;
        }
        
        $all = [];
        foreach ($capitalMinusBeforehand as $m => $list) {
            if($type==1){
                db('capital_minus_beforehand')->where(['minus_id'=>$list['minus_id']])->where('delete_time',0)->delete();
            }else{
                db('capital_minus_beforehand')->where(['minus_id'=>$list['minus_id']])->where('delete_time',0)->update(['delete_time'=>time()]);
            }
           
            $detailedList = [1, 2];
            $capital      = db('capital')->where(function ($quer) {
                $quer->where('capital.approve', 0)->whereOr('capital.approve', 1)->whereOr('capital.approve', 2);
            })->where('capital.types', 1)->where('capital.enable', 1)->join('detailed', 'detailed.detailed_id=capital.projectId', 'left')->join('app_user_order_capital', 'app_user_order_capital.capital_id=capital.capital_id and app_user_order_capital.deleted_at is null', 'left')->where('capital.ordesr_id', $orderId)->where(function ($query) use ($detailedList) {
                foreach ($detailedList as $value) {
                    $query->whereOrRaw("FIND_IN_SET({$value}, detailed.reimbursement) > 0", [], 'string');
                }
            })->where('detailed.detailed_category_id', $list['detailed_category_id'])->field(['(capital.labor_cost+capital.labor_cost_material) as labor_cost', 'capital.to_price', 'capital.labor_cost_reimbursement', '(SELECT COALESCE(SUM(personal_price + cooperation_price), 0) FROM app_user_order_capital WHERE app_user_order_capital.capital_id = capital.capital_id AND app_user_order_capital.deleted_at IS NULL) as total_personal_cooperation_price', 'capital.capital_id', 'capital.ordesr_id', 'detailed.reimbursement'])->where('capital.capital_id', '<>', $list['minus_id'])->group('capital.capital_id');
            
            $capital = $capital->select();
//            if (empty($capital)) {
//                return['code'=>300, 'msg'=>"因该清单工费额度已被发放或报销，无法减项，若仍然要减项，请企业微信提交特殊审批，通过后联系张斌"];
//            }
            foreach ($capital as $k => $item) {
                $priceMoney                                      = db('reimbursement_capital_beforehand')->where('reimbursement.status', 0)->where('reimbursement_capital_beforehand.capital_id', $item['capital_id'])->join('reimbursement', 'reimbursement.id=reimbursement_capital_beforehand.reimbursement_id', 'left')->sum('reimbursement_capital_beforehand.beforehand_money');
                $capital_minus_beforehand                        = db('capital_minus_beforehand')->where('capital_minus_beforehand.delete_time', 0)->where('capital_minus_beforehand.capital_id', $item['capital_id'])->sum('capital_minus_beforehand.beforehand_money');
                $capital[$k]['labor_cost']                       = $capital[$k]['labor_cost'] - $capital_minus_beforehand;
                $capital[$k]['labor_costs']                      = $item['labor_cost'];
                $capital[$k]['reimbursement_capital_beforehand'] = $priceMoney;
                $capital[$k]['types']                            = $list['types'];
                $capital[$k]['totalPriceSum']                    = (string)(bcsub($item['labor_cost'], ($item['labor_cost_reimbursement'] + $item['total_personal_cooperation_price'] + $priceMoney + $capital_minus_beforehand), 3));
            }
            $allocationAmount = $list['labor_cost_reimbursement'];
            $chao             = [];
            foreach ($capital as $k => $item) {
                $op                   = array_sum(array_column($capital, 'totalPriceSum'));
                $capital[$k]['keSum'] = $op;
                $capital[$k]['bi']    = empty($capital[$k]['keSum']) ? 0 : (string)$item['totalPriceSum'] / $capital[$k]['keSum'];
                if ($k == count($capital) - 1) {
                    $capital[$k]['fen'] = (string)($allocationAmount - array_sum(array_column($capital, 'fen')));
                    if ($capital[$k]['fen'] > $item['totalPriceSum']) {
                        $capital[$k]['fen'] = $item['totalPriceSum'];
                    }
                } else {
                    $capital[$k]['fen'] = (string)round($allocationAmount * $capital[$k]['bi'], 2);
                    if ($capital[$k]['fen'] > $item['totalPriceSum']) {
                        $capital[$k]['fen'] = $item['totalPriceSum'];
                    }
                }
                
                
            }
            $listArray        = [];
            $tageList         = [];
            $tageList['chao'] = (string)($allocationAmount - array_sum(array_column($capital, 'fen')));
            $to_price         = max(array_column($capital, 'to_price'));
            foreach ($capital as $k => $g) {
                array_push($listArray, ['beforehand_money' => $g['fen'], 'capital_id' => $g['capital_id'], 'minus_id' => $list['minus_id'], 'types' => $g['types'], 'create_time' => time()]);
                if ($g['to_price'] == $to_price) {
                    $tageList['capital_id'] = $g['capital_id'];
                    $tageList['labor_cost'] = $g['labor_costs'];
                }
                
            }
            db('capital_minus_beforehand')->insertAll($listArray);
            $all[] = $tageList;
        }
       
        if (!empty($all)) {
            $result = [];
            foreach ($all as $item) {
                $relationId = $item['capital_id'];
                // 检查$result数组中是否已经有这个relation_id的条目
                if (!isset($result[$relationId])) {
                    // 如果没有，则添加一个新条目，并初始化change_value为当前条目的值
                    $result[$relationId] = ['capital_id' => $relationId, 'chao' => $item['chao'], 'labor_cost' => $item['labor_cost'],
                    
                    ];
                } else {
                    // 如果已经存在，则累加change_value
                    $result[$relationId]['chao'] += $item['chao'];
                }
            }
            $indexedResult   = array_values($result);
//            if($types == 3){
//                $approval_bef    = db('approval_bef', config('database.zong'))->where('approval_id', $list['uniqueNumber'])->order('id desc')->where('type', 10)->find();
//            }else{
//                $approval_bef    = db('approval_bef', config('database.zong'))->where('approval_id', $capital_id)->order('id desc')->where('type', 6)->find();
//            }
           
            $approval_record = db('approval_record', config('database.zong'))->where('order_id',$orderId)->where('status',0)->select();
            foreach ($approval_record as $b) {
                if(!in_array($b['relation_id'],array_column($indexedResult,'capital_id'))){
                    db('approval_record', config('database.zong'))->where('id', $b['id'])->update(['change_value'=>0]);
                }
                foreach ($indexedResult as $a) {
                    if ($a['chao']>0 && $b['change_value'] != $a['chao']  && $b['relation_id'] == $a['capital_id']) {
                        db('approval_record', config('database.zong'))->where('id', $b['id'])->update(['change_value'=>$a['chao']]);
                    }
                    
                }
            }
            
        }
        
    }
    /**完工更行订单延期扣款和完工验收单
     * Summary of allCompleted
     * @param mixed $order_id
     * @return void
     */
    public function allCompleted($order_id, $userInfo)
    {
        $order = db('order')->join('order_aggregate', 'order.order_id=order_aggregate.order_id', 'left')->join('startup', 'order.order_id=startup.orders_id', 'left')->where('order.order_id', $order_id)->field('order.finish_time,order.agency_finish_time,order_aggregate.main_price,order_aggregate.agent_price,startup.up_time')->find();
        $deadline_time = 0;
        if ($order['main_price'] == 0 && $order['agent_price'] != 0 && !empty($order['agency_finish_time'])) {
            $deadline_time = $order['agency_finish_time'];
        }
        if ($order['main_price'] != 0 && $order['agent_price'] == 0 && !empty($order['finish_time'])) {
            $deadline_time = $order['finish_time'];
        }
        if ($order['main_price'] != 0 && $order['agent_price']  != 0 && !empty($order['finish_time']) && !empty($order['agency_finish_time'])) {
            $deadline_time = max([$order['finish_time'], $order['agency_finish_time']]);
        }
        if ($deadline_time > 0) {
            Db::connect(config('database.zong'))->table('order_delay_deduction')->where(['order_id' => $order_id])->update(['delete_time' => time()]);
            if ($userInfo['completion_acceptance'] == 1) {
                $work_check_id    = db('work_check')->where(['work_check.type' => 1, 'order_id' => $order_id, 'work_check.work_title_id' => 5])->where('delete_time', 0)->find();
                $order_completion = Db::connect(config('database.zong'))->table('order_completion')->where(['work_check_id' => $work_check_id['id'], 'order_id' => $order_id, 'inspection_type' => 0])->count();
                if ($order_completion == 0) {
                    Db::connect(config('database.zong'))->table('order_completion')->insert(['work_check_id' => $work_check_id['id'], 'order_id' => $order_id, 'deadline_time' => strtotime(date('Y-m-d 23:59:59', $deadline_time + 3 * 86400)), 'create_time' => $deadline_time]);
                } else {
                    Db::connect(config('database.zong'))->table('order_completion')->where(['work_check_id' => $work_check_id['id'], 'order_id' => $order_id, 'inspection_type' => 0])->update(['deadline_time' => strtotime(date('Y-m-d 23:59:59', $deadline_time + 3 * 86400)), 'create_time' => $deadline_time]);
                }
            }

            $day = floor($deadline_time - $order['up_time']) / (3600 * 24);
            if ($day > 0) {
                Db::connect(config('database.zong'))->table('order_delay_deduction')->insert(['finished_time' => $deadline_time, 'order_id' => $order_id, 'create_time' => time(), 'state' => 0, 'day' => $day]);
            }
        }
    }
     /**
     * 检查指定用户最近3天是否上下半天都有安排
     * @param int $userId 用户ID
     * @return bool 是否满足条件
     */
    public function checkHasFullSchedule($userIds)
    {
        if (empty($userIds)) {
            return [];
        }

        // 获取最近3天的日期时间戳（0点）
        $today = strtotime(date('Y-m-d'));
        $yesterday = $today - 86400;
        $dayBeforeYesterday = $yesterday - 86400;
        $dates = [$today, $yesterday, $dayBeforeYesterday];

        // 批量查询满足条件的用户
        $result = Db::connect(config('database.db2'))->table('app_user_scheduling')
            ->where('user_id', 'in', $userIds)
            ->where('date', 'in', $dates)
            ->where('arrangement', 1)
            ->whereNull('deleted_at')
            ->where('day', 'in', ['0.5', '-0.5'])
            ->group('user_id, date')
            ->having('COUNT(DISTINCT day) = 2')
            ->select();

        // 统计每个用户满足条件的天数
        $userValidDays = [];
        foreach ($result as $row) {
            $userId = $row['user_id'];
            if (!isset($userValidDays[$userId])) {
                $userValidDays[$userId] = 0;
            }
            $userValidDays[$userId]++;
        }

        // 组装结果：只有满足3天都有完整安排的用户才返回true
        $finalResult = [];
        foreach ($userIds as $userId) {
            $finalResult[$userId] = isset($userValidDays[$userId]) && $userValidDays[$userId] == 3;
        }

        return $finalResult;
    }
    
    /**
     * 检查指定用户最近3天是否至少有0.5天（一个半天）没有安排
     * @param int $userId 用户ID
     * @return bool 是否有空闲
     */
    public function checkHasFreeTime($userId)
    {
        // 获取最近3天的日期时间戳（0点）
        $today = strtotime(date('Y-m-d'));
        $yesterday = $today - 86400;
        $dayBeforeYesterday = $yesterday - 86400;
        $dates = [$today, $yesterday, $dayBeforeYesterday];
        
        // 计算最近3天有安排的半天总数（最多6个半天）
        $scheduledCount = Db::connect(config('database.db2'))->table('app_user_scheduling')->where('user_id', $userId)
            ->where('date', 'in', $dates)
            ->where('arrangement', 1)
            ->whereNUll('deleted_at')
            ->where('day', 'in', ['0.5', '-0.5'])
            ->count();
        
        // 如果有安排的半天少于6个，说明存在空闲
        return $scheduledCount < 6;
    }
    /**
     * 查询现有待审核的材料
     */
    public function materialsPendingReview($store_id, $invclasscode)
    {
        $store_megre = db('store_megre', config('database.zong'))->order('id desc')->where('state', 1)->where('store_id', $store_id)->find();
         $order = db('order');
        if (!empty($store_megre)) {
            $store_megre_store_id = db('store_megre', config('database.zong'))->order('id desc')->where('state', 1)->where('m_store_id', $store_megre['m_store_id'])->column('store_id');
          
            $order->whereIn('store_id',$store_megre_store_id);

        }else{
             $order = db('order')->where('store_id', $store_id);
        }
        $order_id =$order->whereIn("state",[4,7])->where('order.cleared_time is  null or order.cleared_time =0')->column('order.order_id');
        // echo  $order->getLastSql();die;
        $materialUsage = [];
        if (!empty($order_id)) {
            $materialUsage = db('material_usage')
                ->join('order', 'order.order_id = material_usage.order_id', 'left')
                ->whereIn('code', $invclasscode)
                ->where('material_usage.status', 0)
                ->whereIn('order.order_id', $order_id)
                ->group('code')
                ->column('SUM(square_quantity) as total', 'code');
        }
      
        // 3.4 批量查询 secondment（按 code 分组求和，一次查询）
        $secondment = db('secondment')
            ->whereIn('code', $invclasscode)
            ->whereIn('status', [0, 3])
            ->where('lender_store_id', $store_id) // 注意：原代码是 whereIn，此处应为 where（单个store_id）
            ->column('SUM(number) as total', 'code');
        // 3.5 合并结果（按 invclcode 汇总）
        $result = [];
        foreach ($invclasscode as $code) {
            $mu = $materialUsage[$code] ?? 0;
            $s = $secondment[$code] ?? 0;
            $result[$code] = bcadd($mu, $s, 2);
        }
        return $result;
    }
}
